You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否用filter函数或守卫改写Haskell的countPositives函数?如何实现?

如何用filter或守卫实现统计列表正数个数的函数?

你已经用列表推导式实现了统计列表中正数个数的函数,代码如下:

countPositives :: [Int] -> Int 
countPositives xs = length [ x | x <- xs, x > 0]

下面分别给出用filter函数和守卫结合递归的实现方式:

用filter函数实现

filter的作用就是筛选出列表中符合条件的元素,直接把它和length结合就能实现需求:

countPositives :: [Int] -> Int
countPositives xs = length (filter (> 0) xs)

如果习惯柯里化风格,还可以省略参数,写成更简洁的形式:

countPositives :: [Int] -> Int
countPositives = length . filter (> 0)

用守卫结合递归实现

利用递归遍历列表,通过守卫判断当前元素是否为正数,逐步累加计数:

countPositives :: [Int] -> Int
countPositives [] = 0  -- 空列表没有正数,返回0
countPositives (x:xs)
  | x > 0     = 1 + countPositives xs  -- 当前元素是正数,计数加1后递归处理剩余列表
  | otherwise = countPositives xs      -- 当前元素非正,直接递归处理剩余列表

内容的提问来源于stack exchange,提问作者txm03

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 14:25:18