首页 > 解决方案 > 在 Haskell 中,使用给定列表中的重复元素创建一个包含子列表的列表

问题描述

我正在尝试从此更改列表:[0,0,0,1,1,1,2,2,2]

到这样的列表:[[0,0,0], [1,1,1], [2,2,2]]

我被限制只使用前奏而不使用递归,这使得这更加困难。

标签: haskell

解决方案


我的回答是这个问题的答案的变体。

  1. foldr来自前奏曲
  2. stepFn不是递归的
task4 :: [Int] -> [[Int]]
task4 cs = foldr stepFn [[]] cs
  where
    stepFn c [[]]          = [[c]]  -- simple case
    stepFn c ((s:xs) : ps) =        -- please try to write the rest

if(c==s) then (c:c:xs):ps else [c]:((s:xs):ps)

测试:

Prelude> task4 [0,0,0,1,1,1,2,2,2]
[[0,0,0],[1,1,1],[2,2,2]]
Prelude> task4 [0,0,1,1,1,2,2]
[[0,0],[1,1,1],[2,2]]

推荐阅读