![](/img/trans.png)
[英]Couldn't match expected type [a] with actual type `Integer -> [Integer]'
[英]Couldn't match expected type ‘[Integer]’ with actual type ‘Integer’
我正在創建一個小於或等於4,000,000的斐波那契數列中所有偶數的列表。 在Haskell中,我將斐波那契數列定義為:
fibs = 1 : 2 : next fibs
where
next (a : t@(b:_)) = (a+b) : next t
並且正在使用以下列表理解來構建我的集合:
[ x | x <- take 50 fibs, x `mod` 2 == 0, last x <= 4*10^6 ]
但是,GHC拋出了Couldn't match expected type '[Integer]' with actual type 'Integer'
錯誤Couldn't match expected type '[Integer]' with actual type 'Integer'
。
我知道謂詞last x <= 4*10^6
會導致錯誤。 受到hammar 在這里的回答的啟發,我的最初反應是確保4*10^6
是正確的類型,因此我嘗試將謂詞改寫為last x <= toInteger 4*10^6
無效。 同樣的錯誤。 我還認為也許我需要將4*10^6
指定為一個單例(即[4*10^6]
),但是那里也沒有運氣。
我正在努力了解到底發生了什么以及如何最好地解決該問題。
sum [ x | x <- take 50 fibs, x `mod` 2 == 0, last x <= 4*10^6 ]
take 50 fibs
是一個Integer
( [Integer]
)的列表, x
是該列表的元素(因此是Integer
)。 last
是一個需要列表的函數...
GHCi> :t last
last :: [a] -> a
...但是您要傳遞一個Integer
。 您不需要last
過濾列表理解中的元素。 只需使用:
sum [ x | x <- take 50 fibs, x `mod` 2 == 0, x <= 4*10^6 ]
順便說一句,假設您知道fibs
中的數字總是在增加,則可以將表達式寫為:
-- (<= 4*10^6) is shorthand for (\x -> x <= 4*10^6)
sum [ x | x <- takeWhile (<= 4*10^6) fibs, x `mod` 2 == 0 ]
-- Three equivalent alternatives:
(sum . takeWhile (<= 4*10^6)) [ x | x <- fibs, x `mod` 2 == 0 ]
(sum . takeWhile (<= 4*10^6) . filter (\x -> x `mod` 2 == 0)) fibs
(sum . takeWhile (<= 4*10^6) . filter ((== 0) . (`mod` 2))) fibs
這樣,您就不需要任意限制50個元素。
fibs :: [Integer]
take 50 fibs :: [Integer]
x <- take 50 fibs
x :: Integer
last :: [a] -> a
last x :: ???
如果您刪除last
則列表理解將進行類型檢查。 我想你打算寫的東西更像
[ x | x <- takeWhile (<= 4*10^6) $ take 50 fibs, x `mod` 2 == 0 ]
雖然。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.