如何才能更好地查找列表的长度?

1 recursion haskell compiler-errors

我正在做一个代码来查找列表的长度,使用递归,但是有很多错误.我是一个非常初学者,我不能很好地Haskell.这是代码:

longListe :: [a] -> a

longListe [] = error "Empty liste"
longListe [x]= 1
longListe n = 1 + longListe (n-1)
main = print $ longListe
Run Code Online (Sandbox Code Playgroud)

和错误:

 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
Run Code Online (Sandbox Code Playgroud)

有人能帮帮我吗.谢谢

Tho*_*ois 5

问题在于函数的类型定义:longListe :: [a] -> a.

如果您拨打longListe号码列表,它可以正常工作.例如,如果您打电话longListe [1,2,3],则输入将是[Int] -> Int.

但是,如果您尝试获取字符串列表的长度,则此类型将变为[String] -> String.这不是你想要的,因为你想要返回一个数字.

您得到的错误表明:

没有(字母a)来自字面'1'的实例

由于您返回一个数字并在输入时执行数值运算,因此编译器a应该是一个数字,因此提到错误(Num a).

如果你改变定义longListe :: [a] -> Int,它应该更好(实际上它仍然不会工作,但出于不同的原因,但我会让你自己尝试解决这个问题,因为这是最好的学习方法).

此外,有没有理由为什么空列表应该错误而不是返回0?