簡體   English   中英

無法將預期類型“ [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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM