![](/img/trans.png)
[英]Haskell Couldn't match expected type `Integer' with actual type `[Integer]'
[英]Couldn't match expected type [a] with actual type `Integer -> [Integer]'
我有以下代碼,先找到一個整數的除數,然后找到除數的所有子集,然后求和每個子集中的所有除數,然后進行測試以查看該整數是否在求和列表中表示。 在findWeird中,這是對整數列表執行的。
allSubsets :: (Integral a ) => [a] -> [[a]]
allSubsets [] = [[]]
allSubsets ( n : nr ) = allSubsets nr ++ map (n:) (allSubsets nr)
sumAllSubsets :: (Integral a ) => [a] -> [a]
sumAllSubsets s = map sum (allSubsets s)
allDivisors :: (Integral a) => a -> [a]
allDivisors 0 = []
allDivisors n | n > 0 = [d | d <- [1..n], n `mod` d == 0]
| n < 0 = -1 : allDivisors (-n)
findWeird :: (Integral a) => [a] -> [a]
findWeird [] = []
findWeird (n:nn) = ( if n `elem` (AS.sumAllSubsets (DFL.allDivisors))
then []
else [n]) ++ findWeird nn
問題是我得到了錯誤:
test.hs:15:61:
Couldn't match expected type `[a]' with actual type `Integer -> [Integer]' In the first argument of `sumAllSubsets', namely `(allDivisors)' In the second argument of `elem', namely `(sumAllSubsets (allDivisors))' In the expression: n `elem` (sumAllSubsets (allDivisors))
但是就目前所知,allDivisors產生一個[Integral],sumAllSubsets產生一個[Integral],所以我只是想知道是否有人可以提供幫助。 謝謝。
我認為問題是您實際上並未將allDivisors
應用於任何事物:
AS.sumAllSubsets (DFL.allDivisors)
只是將sumAllSubsets
應用於函數 allDivisors
,而不是其[Integer]
返回值。 也許您是說AS.sumAllSubsets (DFL.allDivisors n)
,也就是說,將allDivisors
應用於n
?
(順便說一句, findWeird
只是做一個filter
,可以寫成
findWeird nn = filter (\n -> n `notElem` (sumAllSubsets $ allDivisors n)) nn
在這里我還通過($)
運算符自由地減少了一些嵌套。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.