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

Haskell如何同时统计列表中的正数与负数数量?

同时统计列表中正数和负数的数量

这里有几种实现方式,你可以根据需求选择:

方式一:直观的列表推导式(遍历两次列表)

这种写法最容易理解,分别用列表推导式筛选正数和负数,再取它们的长度:

countPosNeg :: [Int] -> (Int, Int)
countPosNeg xs = (length [x | x <- xs, x > 0], length [x | x <- xs, x < 0])

调用countPosNeg [1,2,3,-1,-2]会返回(3,2),符合你的预期。

方式二:使用partition函数(遍历一次半列表)

利用Data.List中的partition函数先拆分出正数,再从剩余元素中过滤出负数,比两次遍历更高效:

import Data.List (partition)

countPosNeg :: [Int] -> (Int, Int)
countPosNeg xs = let (positives, others) = partition (> 0) xs
                     negatives = filter (< 0) others
                 in (length positives, length negatives)

方式三:用foldl一次遍历完成(最高效)

通过foldl遍历列表一次,同时累加正数和负数的计数,适合处理大列表:

countPosNeg :: [Int] -> (Int, Int)
countPosNeg = foldl updateCounts (0, 0)
  where updateCounts (pos, neg) x
          | x > 0     = (pos + 1, neg)
          | x < 0     = (pos, neg + 1)
          | otherwise = (pos, neg)  -- 忽略0的情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 17:15:37