Haskell:从输入列表创建列表元组 [英] Haskell: create a tuple of lists from an input list

查看:51
本文介绍了Haskell:从输入列表创建列表元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置一些功能来帮助我正在处理的当前项目.我是Haskell的新手,正在努力实现所需的功能.

I am trying to set up some functions to help with a current project I am working on. I am new to Haskell and struggling to implement my desired functions.

我有一个列表 [a] ,并希望它输出包含四个不同列表的元组([b],[b],[b],[b]),其中列表 [a] 中的每个项目都连续放置到输出元组中的下一个列表中.因此,输入列表 [a] 中的第一个元素转到第一个列表 [b] [a] 中的第二个元素转到第二个列表 [b] [a] 中的第三个元素转到第三个列表 [b] ,依此类推.我尝试使用chunksOf和splitEvery/splitAt,但是无法获得正确的输出.并且帮助将不胜感激!谢谢!

I have a list [a] and would like it to output a tuple of four different lists ([b],[b],[b],[b]) where each item in list [a] is successively placed in to the next list in the output tuple. So the first element in the input list [a] goes to the first list [b], the second element in [a] goes to the second list [b], the third element in [a] goes to the third list [b], and so on. I have tried using chunksOf and splitEvery/splitAt but cannot get the correct output. And help would be greatly appreciated! Thanks!

推荐答案

您每次旋转 "四元组并添加到第一个元素.因此,我们可以使用类似如下的 folder 模式来实现此目的:

You each time "rotate" the 4-tuple and prepend to the first element. So we can implement this with a foldr pattern that looks like:

toFour :: [a] -> ([a], [a], [a], [a])
toFour = foldr (\a (bs, cs, ds, as) -> (a:as, bs, cs, ds)) ([], [], [], [])

或具有不可辩驳的模式:

or with an irrefutable pattern:

toFour :: [a] -> ([a], [a], [a], [a])
toFour = foldr (\a ~(bs, cs, ds, as) -> (a:as, bs, cs, ds)) ([], [], [], [])

因此,这里(bs,cs,ds,as)是我们为列表尾部生成的4元组,我们向右旋转"以构造元组(as,bs,cs,ds),然后将项目 a 放在4元组的第一个列表中.

So here (bs, cs, ds, as) is the 4-tuple that we generated for the tail of the list, and we "rotate" to the right to construct the tuple (as, bs, cs, ds) and then prepend the item a to the first list of the 4-tuple.

对于整数列表,这可以给我们:

For a list of integers, this gives us:

Prelude> toFour [1..2]
([1],[2],[],[])
Prelude> toFour [1..3]
([1],[2],[3],[])
Prelude> toFour [1..4]
([1],[2],[3],[4])
Prelude> toFour [1..5]
([1,5],[2],[3],[4])
Prelude> toFour [1..6]
([1,5],[2,6],[3],[4])
Prelude> toFour [1..10]
([1,5,9],[2,6,10],[3,7],[4,8])

当我们使用不可辩驳的模式时,这是懒惰的,因此我们可以例如分配无限列表的元素,然后例如获取第二项的前10个元素:

When we work with the irrefutable pattern, this is done lazily, so we can for example distribute elements of an infinite list, and then take for example obtain the first 10 elements of the second item:

Prelude> (\(_, l, _, _) -> take 10 l) (toFour [1..])
[2,6,10,14,18,22,26,30,34,38]

这篇关于Haskell:从输入列表创建列表元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆