haskell - 在 Haskell 中,使用给定列表中的重复元素创建一个包含子列表的列表
问题描述
我正在尝试从此更改列表:[0,0,0,1,1,1,2,2,2]
到这样的列表:[[0,0,0], [1,1,1], [2,2,2]]
我被限制只使用前奏而不使用递归,这使得这更加困难。
解决方案
我的回答是这个问题的答案的变体。
foldr
来自前奏曲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]]
推荐阅读
- google-cloud-firestore - Firestore SecurityRules get () 问题
- azure-web-app-service - 在 Azure 上远程调试 Blazor WASM?
- java - java模块版本不匹配
- javascript - “grant_type 参数丢失”:Spotify API PKCE OAuth 流程问题
- javascript - 如何使用文件名从谷歌电子表格复制数据,并将其粘贴到另一个文件中?
- pandas - 熊猫合并两个数据框创建数百万条记录
- numpy - pytorch/numpy中meshgrid的使用
- https - Boost asio 同步 https 调用 - Json 响应具有意外字符
- json - JSON - 按字符串过滤数组
- python - 在循环中取消引用列表时出错