[英]In Haskell how to count the number of a specific Int in a list
我试图创建一个countElems
一个Int
和一个[Int]
的函数countElems
,并返回列表中该特定Int
数量。 到目前为止,我有:
countElems :: Int -> [Int] -> Int
countElems n (x:xs)
| xs == [] = 0
| n == x = 1 + countElems n xs
| n /= x = countElems n xs
运行时,这似乎可行,但是在进一步检查时,如果输入countElems 9 [5, 3, 9, 3, 9]
则输出为1
而不是2
。 我可以看到这是因为它在查看n == x
导致错误输出之前会检查xs == []
,但是如果我调换这两种情况,则表示Non-exhaustive pattern
。
经过进一步思考后编辑:
我可以消除此代码发布的错误@ user2407038:
countElems :: Int -> [Int] -> Int
countElems _ [] = 0
countElems n (x:xs)
| n == x = 1 + countElems n xs
| n /= x = countElems n xs
看起来不太优雅,但功能相同吗?
另一个没有任何递归子句的:
countElem e = length . filter (e ==)
第一次检查( xs == [] = 0
)时,您忘记检查x==n
是否为1
而不是0
:
countElems n (x:xs)
| xs == [] = if x==n then 1 else 0
| n == x = 1 + countElems n xs
| n /= x = countElems n xs
另一个(可能更直接)的实现可能会整体上看一下列表:
cE n [] = 0
cE n (x:xs) = (if n==x then 1 else 0) + (cE n xs)
不管您按哪个顺序放置警卫,您的功能都并不详尽。考虑countElems 9 []
。 这是一个错误,因为没有模式匹配空列表。 (也许这是您的情况所希望的行为-但通常错误很严重)。 考虑在此处使用模式匹配:
countElems n (x:xs) = fromEnum (n == x) + countElems n xs
countElems _ [] = 0
fromEnum
避免了我喜欢的fromEnum
if
,但是您不必使用它。
在这里可能不需要使用显式递归。 尝试\\x = length . filter (==x)
\\x = length . filter (==x)
。
您也可以使用map编写它:
countElems :: Int -> [Int] -> Int
countElems n xs = sum $ map (fromEnum . (==n)) xs
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.