2012-12-13 54 views
2

我在Haskell中有兩個代碼是相同的,都必須在給定的位置(參數n)分割一個列表,但一個工作的時候另一個不是,爲什麼會這樣呢?等效代碼,一個工作,而另一個不工作

divide [] _ = ([],[]) 
divide (h:t) n 
     | n>0 = (h:list1 , list2) 
     | otherwise = ([],h:t) 
     where (list1, list2) = divide t (n-1) 

上面的代碼工作得很好,但下面的代碼沒有。

divide [] _ = ([],[]) 
divide (h:t) n 
     | n>0 = (h:(divide t (n-1)) , divide t (n-1)) 
     | otherwise = ([],h:t) 

ghci中提供了以下信息:

divide.hs:3:29:

Couldn't match expected type '[a0]' with actual type '([a0], [a1])' 
    In the return type of a call of 'divide' 
    In the second argument of '<:>', namely ' divide t (n-1) ' 
    In the expression: h: divide t (n-1) 

編輯:

剛一說明,我假設那

where (list1, list2) = divide t (n-1) 

相當於

where list1 = divide t (n-1) 
     list2 = divide t (n-1) 

是我的假設嗎?錯誤的假設可能導致更糟糕的結論。

+2

我認爲這個錯誤是不言自明的。 'divide t(n-1)'給出一個元組而不是一個列表,所以你不能在'h:(divide t(n-1)'中追加'h'。類似的情況是另一部分因爲它必須是列表,而不是一個元組再次。 – Satvik

+0

嗯,看到你的評論後,我的編輯,現在我明白我的代碼上發生了什麼 – user1493813

+0

學習愛「無法匹配預期類型Blah與實際類型BlahBlah」來自編譯器的消息,一旦你明白如何閱讀它們,它們是非常豐富的。 –

回答

9

你的假設是錯誤的。

where (list1, list2) = divide t (n-1) 

相當於

where pair = divide t (n-1) 
     list1 = fst pair 
     list2 = snd pair 

左手邊(list1, list2)是被反對的右手側懶惰地匹配的圖案。它不會將相同的值分配給多個變量。

相關問題