【发布时间】:2016-04-02 01:49:26
【问题描述】:
我有一个列表,它只能包含两种元素,Apple 和 Peach。我需要创建一个函数,给定一个包含这些元素的列表,使用递归返回列表中 Apple 的出现次数。
这是我的尝试:
data Fruit = Apple | Peach
findFruit :: [Fruit] -> Int
findFruit [] = 0
findFruit (y:ys)
| y==Apple = 1+(findFruit ys)
| otherwise = findFruit ys
但它不起作用。我怀疑问题出在最后的说明中,但由于我还是 Haskell 新手,我无法真正理解在哪里。
这是错误日志:
Main.hs:7:8:
No instance for (Eq Fruit) arising from a use of ‘==’
In the expression: y == Apple
In a stmt of a pattern guard for
an equation for ‘findFruit’:
y == Apple
In an equation for ‘findFruit’:
findFruit (y : ys)
| y == Apple = 1 + (findFruit ys)
| otherwise = findFruit ys
Failed, modules loaded: none.
感谢您的帮助!
【问题讨论】:
-
使用模式匹配而不是守卫。正如在
findFruit (Apple:xs) = ... ; findFruit (Peach:xs) = ...中一样,添加deriving Eq作为答案建议也将起作用,但模式匹配是惯用且更可取的。 -
顺便说一下 - 如果你调用你的函数
findFruit我会期待不同的类型签名,如果你这样做是为了练习尝试实现countFruit :: Fruit -> [Fruit] -> Int。