首页 > 解决方案 > 哈斯克尔。变量不在范围内:howManyTimes :: Integer -> [Integer] -> t

问题描述

我写了一个小代码,它计算列表中的字符或数字以及多少次。例如 howManyTimes 3 [2, 3, 4, 5, 3, 3, 1, 80, 3] 应该是 4

这是我的代码

howManyTimes y [] = 0
howManyTimes y xs = howManyIntern y (x:xs) acc 
                        | x == y = howManyIntern y xs (acc + 1)
                        | otherwise = howManyIntern y xs acc  

我收到此错误消息。变量不在范围内:howManyTimes :: Integer -> [Integer] -> t

谁能给我一个提示?

标签: haskell

解决方案


我已经重写了我的代码。我不再收到错误但输出为 0

howManyTimes y xs = howManyIntern y xs 0 
    where howManyIntern y [] acc = 0 
          howManyIntern y (x:xs) acc | x == y = howManyIntern y xs (acc + 1) 
                                     | otherwise = howManyIntern y xs acc 

由于表达式:

howManyIntern y [] acc = 0 

每当它完成计数时返回 0。很容易通过 returnacc来修复:

howManyIntern y [] acc = acc

另一种使用现有功能的方法:

howManyTimes y xs = length $ filter (==y) xs

推荐阅读