[英]How can I be better my code to find out the length of a list?
我正在做一个代码,使用递归来找出列表的长度,但是有很多错误。 我是一个非常初学者,但我对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
有人能帮帮我吗。 谢谢
问题在于函数的类型定义: longListe :: [a] -> a
。
如果您在数字列表上调用longListe
,则效果很好。 例如,如果调用longListe [1,2,3]
,则键入将为[Int] -> Int
。
但是,如果尝试获取字符串列表的长度,则此类型变为[String] -> String
。 这不是您想要的,因为您要返回一个数字。
您收到的错误表明:
没有(Num a)的实例来自文字'1'
由于您返回数字并使用输入进行数字运算,因此编译器期望a
为数字,因此出现错误提示(Num a)
。
如果将定义更改为longListe :: [a] -> Int
,它应该会更好地工作(实际上它仍然无法工作,但是出于不同的原因,但是我将让您尝试自己解决此问题,因为这是最好的方法学习方式)。
另外,是否有任何原因导致空列表应该出错而不是返回0?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.