我有一个列表,它只能包含两种元素:Apple和Peach。我需要创建一个函数,给定一个包含这些元素的列表,该函数使用递归返回Apple在列表中出现的次数。
\n\n这是我的尝试:
\n\ndata Fruit = Apple | Peach\nfindFruit :: [Fruit] -> Int\n\nfindFruit [] = 0\n\nfindFruit (y:ys)\n | y==Apple = 1+(findFruit ys)\n | otherwise = findFruit ys\nRun Code Online (Sandbox Code Playgroud)\n\n但它不起作用。我怀疑问题出在最后的指令中,但我无法真正理解哪里,因为我仍然是 Haskell 新手。
\n\n这是错误日志:
\n\nMain.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.\nRun Code Online (Sandbox Code Playgroud)\n\n感谢您的帮助!
\n您可以保留数据定义不变并使用模式匹配:
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)