再帰を使用してリストの長さを調べるコードを実行していますが、多くのエラーがあります。私は非常に初心者であり、私はうまくハスケルできません。ここ はコードです:リストの長さを調べるためにコードを改善するにはどうすればよいですか?
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
誰かが私を助けてくださいすることができます。ありがとう
1つの問題:あなたは '(n-1)'を実行していますが、 'n'はリストです。リストに対して整数演算を実行することはできません。 – dvaergiller
なぜ 'longListe'は空のリストに0を返すのではなく、エラーを発生させるのですか? – chepner