所以仍在学习 Haskell 教程...
提出的一个问题是使用以下方法编写一个函数:
count :: Eq a => [a] -> a -> Int
它可以获取数字和值的列表,并告诉您指定的值在列表中出现了多少次。
它说看看你是否可以使用列表理解来编写它,然后再次使用显式递归......
并且,不仅可以用它来计算数字的出现次数,还可以计算字母的出现次数,例如,“s”在“she sells sea shells”中出现了多少次。
所以我得到:
countListComp :: Eq a => [a] -> a -> Int
countListComp [] find = 0
countListComp ys find = length xs
where xs = [xs | xs <- ys, xs == find]
和:
countRecursion :: Eq a => [a] -> a -> Int
countRecursion [] find = 0
countRecursion (x:xs) find
| find == x = 1 + (countRecursion xs find)
| otherwise = countRecursion xs find
所以它可以很好地计算列表中数字的出现次数,如下所示:
ghci > countListComp [1,3,2,3,4,3] 3
3
ghci > countRecursion [6,9,7,9,8,9] 9
3
但是当我查找特定字母时,它会执行以下操作:
ghci > countListComp ["she sells sea shells"] "s"
0
ghci > countRecursion ["she sells sea shells"] "s"
0
它还说尝试计算其他“可数”的东西,比如有多少个列表......所以我尝试了:
ghci > countListComp [[1,2,3],[3,2,1],[4,5,6]] []
0
我的代码有问题吗,或者我没有正确指定要查找的内容?我认为是后者......因为以下有效:
例如,查找“她卖海贝壳”中出现了多少次“s”...我真的必须将每个单独的字母放在引号中,并在引号之间加一个逗号吗?喜欢:
ghci > countRecursion ['s','h','e',' ','s','e','l','l','s',' ','s','e','a',' ','s','h','e','l','l','s'] 's'
6
我是否必须寻找特定的列表?或者有没有办法只查找其中包含任何内容的列表?
最佳答案
countListComp ["she sells sea shells"] "s"
的问题是你有字符串列表。
您的意思可能是countListComp“她卖贝壳”
Sting 只是字符列表的别名。
使用 countListComp [[1,2,3],[3,2,1],[4,5,6]] []
是不同的问题。它不会计算您有多少个列表。它计算您拥有多少个等于 []
的列表。
如果您尝试 countListComp [[1,2,3],[],[4,5,6]] []
或 countListComp [[1,2,3], [3,2,1],[4,5,6]] [3,2,1]
你得到 1
。
关于Haskell - 计算列表中某个值出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53333388/