Haskell if语句不能正常工作

时间:2017-03-10 23:39:01

标签: list haskell if-statement

非常简单的代码。它将从列表中获得第三个项目。

list numbers = if length numbers > 3
then numbers!!(length numbers - 3) 

else "length must be greater than 2"

当我尝试在GHCI上运行时,我不断收到此错误,

*主>清单[2,3,4]

<interactive>:65:7: No instance for (Num [Char])
 arising from the literal     `2'
 Possible fix: add an instance declaration for (Num [Char])
In the expression: 2
In the first argument of `list', namely `[2, 3, 4]'
In the expression: list [2, 3, 4]

1 个答案:

答案 0 :(得分:2)

thenelse子句中两个表达式的类型必须匹配。由于分支的一侧返回一个列表元素,而另一侧返回一个字符串,因此ghci得出结论,列表元素必须是字符串。但是您指定了[2,3,4],其元素是数字。因此投诉:它不知道如何将数字转换为String

请考虑返回MaybeEither值:

list numbers = if length numbers > 3
    then Right (numbers!!(length numbers - 3))
    else Left "length must be greater than 2" -- sic: 3, not 2