Haskell如何递归计算列表中元素的出现次数?

Haskell如何递归计算列表中元素的出现次数?,haskell,recursion,Haskell,Recursion,我试图递归地计算给定元素(数字)在列表中出现的次数 例如,等于2[1,2,3,2,1,2,3]应返回3,表示2在列表中出现的次数 到目前为止我所做的: equals :: Integer -> [Integer] -> Int equals n [] = 0 equals n (x:xs) = if equals n == x then 1 + equals n xs else equals xs 你快到了。当您想调用函数时,请记住给出

我试图递归地计算给定元素(数字)在列表中出现的次数

例如,
等于2[1,2,3,2,1,2,3]
应返回3,表示2在列表中出现的次数

到目前为止我所做的:

equals :: Integer -> [Integer] -> Int

equals n [] = 0

equals n (x:xs) =

    if equals n == x
        then 1 + equals n xs
        else equals xs

你快到了。当您想调用函数时,请记住给出所有必需的参数

equals :: Integer -> [Integer] -> Int

equals n [] = 0

equals n (x:xs)
    | n == x = 1 + equals n xs
    | otherwise = equals n xs

你基本上已经有了解决方案。只有几个小的打字错误需要纠正

equals :: Integer -> [Integer] -> Int
equals n [] = 0
equals n (x:xs) =
    if n == x then
        1 + equals n xs
    else
        equals n xs

特别是,无论何时调用
equals
,都需要向其传递两个参数。因此,递归调用通常应该看起来像
等于nxs
,而不是
等于xs
。类似地,您在
n
x
之间的比较就是:一个比较。它本身不需要进行递归调用,因此它只需要看起来像
n==x

您可以使用
foldl
,因为它必须是递归的吗?是的,它必须递归地完成。我正在努力为即将到来的测试提高递归能力。