2014-01-24 34 views
1

我有這個代碼的麻煩:沒錯與X +的第一要素,第一+第二等開始不可能匹配預期型

listAdd :: Int -> [Int] -> [Int] 

ListAdd x (y:ys) = (x+y):(foldl listAdd y ys) 

它應該添加列表中它的左邊元素。

編譯器說: Couldnt match expected type [Int] with actual type Int.

我不知道是什麼問題。如果有人能告訴我,那將是很棒的。

+1

是大寫的'ListAdd'類型嗎? Haskell函數不能以大寫字母開頭。 – asm

回答

0

看看foldl你作爲傳遞一個函數,它是Int -> [Int] -> [Int]類型的和無法比擬的a -> b -> a,因爲Int是不一樣的類型[Int]

你可能想在這種情況下使用什麼是map

listAdd x ys = map (\y-> x + y) ys 

編輯:另外的功能名稱不應該大寫啓動,除非你的函數實際上是對一些data類的構造函數。

2

你只需將其更改爲

listAdd _ [] = [] 
listAdd x (y:ys) = (x + y) : listAdd y ys 

你不需要摺疊了!只是簡單的遞歸會做。

不過,我會用zipWith (+)改用一個小竅門:

listAdd x xs = zipWith (+) xs (x : xs) 

您不必使用任何明確的遞歸,它適用於任何長度的列表(沒有必要爲[]特殊情況上)

相關問題