问题描述
我想计算列表中正整数/元素的数量.这将返回具有正值的元素,我如何计算元素?想要构造类似count(array(...))的东西.
I would like to count the number of positive integers/elements in the list. This returns the elements with positive values, how can I count the elements? would like to construct something like count(array(...)).
我想查看带有 i ++ 和 foldl 的版本.那将非常有帮助.
I would like to see a version with i++ and foldl. That would be very helpful.
countPositivesRec :: [Int] -> [Int]
countPositivesRec [] = []
countPositivesRec (x:xs) | x >= 0 = x : tl
| otherwise = tl
where tl = countPositivesRec xs
推荐答案
您拥有
filtering p cons x r = if | p x -> cons x r | otherwise -> r
countPositives = length
. filter (> 0)
= foldr (\x r -> r + 1) 0 -- r++
. foldr (filtering (> 0) (:) ) []
= foldr (filtering (> 0) (\x r -> r + 1)) 0
(由于通过组合其减速器变压器折叠 fuse ,a-la "fold用减速器操作替换了缺点,因此,如果要替换缺点,为什么要首先创建缺点无论如何" )和
(since folds fuse by composing their reducer transformers, a-la "fold replaces the cons with a reducer operation, so why create the cons in the first place if it gonna be replaced anyway"), and
filtering (> 0) (\x r -> r + 1) x r
= if | (> 0) x -> (\x r -> r + 1) x r | otherwise -> r
= if | x > 0 -> r + 1 | otherwise -> r
,因此是您想要的具有 fold 和 increment 的版本,
and thus, a version with fold and increment that you wanted,
countPositives = foldr (\x r -> if | x > 0 -> r + 1 | otherwise -> r) 0 -- r++
您可以从这里拿走它.
这篇关于递归循环数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!