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

在Haskell中如何仅用Prelude无递归将连续重复元素分组为子列表

Haskell 连续相同元素分组实现(仅使用Prelude库,无自定义递归)

实现代码

groupConsecutive :: Eq a => [a] -> [[a]]
groupConsecutive = foldr step []
  where
    step x acc
      | not (null acc) && x == head (head acc) = (x : head acc) : tail acc
      | otherwise = [x] : acc

方案说明

  • 实现依赖的所有函数foldr、null、head、tail均属于Prelude标准库,没有引入额外依赖。
  • 没有自定义递归逻辑,所有遍历逻辑由Prelude提供的高阶折叠函数foldr实现,符合使用限制。
  • 效果验证:传入输入样例groupConsecutive [0,0,0,1,1,1,2,2,2],返回结果为[[0,0,0],[1,1,1],[2,2,2]],完全符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 08:45:03