【问题标题】:Transforming a flattened list into a nested list of length 3 [duplicate]将扁平列表转换为长度为 3 的嵌套列表 [重复]
【发布时间】:2018-11-10 07:18:04
【问题描述】:

给定 Haskell 中的扁平列表:

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

和n=3

如何将列表更改为:

[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]

最好是n 是变量的解决方案

【问题讨论】:

标签: haskell


【解决方案1】:

这是一个很好的例子,展示了如何使用展开器:

f n = unfoldr (\xs->if null xs then Nothing else Just (take n xs, drop n xs))

注意它可以接受无限列表为:

take 4 $ f 3 [1..]

给予

[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]

字符

take 4 $ f 3 ['a'..]

给予

["abc","def","ghi","jkl"]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-09
    • 2018-08-27
    • 2017-08-02
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多