我正在做一個代碼來找出一個列表的長度,使用遞歸,但有很多錯誤。我是一個初學者,我不能很好的Haskell。 下面是代碼:如何更好地查找列表長度的代碼?
longListe :: [a] -> a
longListe [] = error "Empty liste"
longListe [x]= 1
longListe n = 1 + longListe (n-1)
main = print $ longListe
和錯誤:
No instance for (Num a) arising from the literal ‘1’
Possible fix:
add (Num a) to the context of
the type signature for longListe :: [a] -> a
In the expression: 1
In an equation for ‘longListe’: longListe [x] = 1
4-1-a.hs:6:31:
No instance for (Num [a]) arising from a use of ‘-’
In the first argument of ‘longListe’, namely ‘(n - 1)’
In the second argument of ‘(+)’, namely ‘longListe (n - 1)’
In the expression: 1 + longListe (n - 1)
4-1-a.hs:7:8:
No instance for (Show ([a0] -> a0))
(maybe you haven't applied enough arguments to a function?)
arising from a use of ‘print’
In the expression: print
In the expression: print $ longListe
In an equation for ‘main’: main = print $ longListe
有人可以幫我。謝謝
一個問題:你正在做'(n-1)'哪裏'n'是一個列表。您不能在列表上執行整數操作。 – dvaergiller
爲什麼'longListe'會產生一個錯誤,而不是爲空列表返回0? – chepner