在 Haskell 中使用递归查找列表中的出现次数

And*_*llo 3 recursion haskell

我有一个列表,它只能包含两种元素:ApplePeach。我需要创建一个函数,给定一个包含这些元素的列表,该函数使用递归返回Apple在列表中出现的次数。

\n\n

这是我的尝试:

\n\n
data Fruit = Apple | Peach\nfindFruit :: [Fruit] -> Int\n\nfindFruit [] = 0\n\nfindFruit (y:ys)\n    | y==Apple = 1+(findFruit ys)\n    | otherwise = findFruit ys\n
Run Code Online (Sandbox Code Playgroud)\n\n

但它不起作用。我怀疑问题出在最后的指令中,但我无法真正理解哪里,因为我仍然是 Haskell 新手。

\n\n

这是错误日志:

\n\n
Main.hs:7:8:\n    No instance for (Eq Fruit) arising from a use of \xe2\x80\x98==\xe2\x80\x99\n    In the expression: y == Apple\n    In a stmt of a pattern guard for\n                   an equation for \xe2\x80\x98findFruit\xe2\x80\x99:\n      y == Apple\n    In an equation for \xe2\x80\x98findFruit\xe2\x80\x99:\n        findFruit (y : ys)\n          | y == Apple = 1 + (findFruit ys)\n          | otherwise = findFruit ys\nFailed, modules loaded: none.\n
Run Code Online (Sandbox Code Playgroud)\n\n

感谢您的帮助!

\n

Mic*_*its 5

您可以保留数据定义不变并使用模式匹配:

data Fruit = Apple | Peach

findFruit :: [Fruit] -> Int
findFruit []         = 0
findFruit (Apple:ys) = 1 + findFruit ys
findFruit (Peach:ys) = findFruit ys
Run Code Online (Sandbox Code Playgroud)