haskell - 哈斯克尔。变量不在范围内: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
谁能给我一个提示?
解决方案
我已经重写了我的代码。我不再收到错误但输出为 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
推荐阅读
- c# - 在 Linux 上的 .netcore 3.0 中找不到类型或命名空间名称“System”(您是否缺少 using 指令或程序集引用?)
- rstudio - 相当于降价演示中的“高度动态”外观
- c++ - 如何使用 SDL2 修复“不支持 GLSL 3.30”错误
- excel - 是否可以获得单元格的“属性”
- python - 使用列表中保存的值从子目录名称中删除子字符串
- java - 应用在setter方法上的@Resource注解在使用getter方法获取值时返回空指针异常
- hyperledger-fabric - 通用连接配置文件缺少此客户的组织和证书颁发机构
- java - java.lang.String类型的value数据无法转成JSONObject@java android
- r - R studio - 我需要使用混淆矩阵的灵敏度和特异性以及阳性和阴性预测值的置信区间
- c# - Asp.net WebService 无法将“System.Int32”类型的对象转换为 ty...neric.IDictionary`2[System.String,System.Object]'