Ich mache einen Code, um die Länge einer Liste mit Rekursion herauszufinden, aber es gibt eine Menge Fehler. Ich bin ein sehr Anfänger und ich kann nicht sehr gut Haskell. Hier ist der Code:Wie kann ich meinen Code verbessern, um die Länge einer Liste herauszufinden?
longListe :: [a] -> a
longListe [] = error "Empty liste"
longListe [x]= 1
longListe n = 1 + longListe (n-1)
main = print $ longListe
und die Fehler:
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
kann jemand mir bitte helfen. Danke
Ein Problem: Sie tun '(n-1)' wo 'n' eine Liste ist. Sie können Integer-Operationen für eine Liste nicht ausführen. – dvaergiller
Warum sollte 'longListe' einen Fehler auslösen anstatt 0 für eine leere Liste zurückzugeben? – chepner