Haskell在不同索引处组合了2个列表的元素 [英] Haskell combine the elements of 2 lists at different index's

查看:35
本文介绍了Haskell在不同索引处组合了2个列表的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不好意思的标题,我不太确定如何用语言来描述它,但这就是我的意思.如果您知道更好的表达方式,请告诉我.

Apologies for the awful title, I'm not too sure how to describe it in words but here is what I mean. If you know a better way to phrase this please let me know.

假设我有2个长度相等的列表.

Suppose I had 2 lists, of equal length.

[a, b, c] [x, y, z]

我要创建列表

[[a, y, z], [b, x, z], [c, x, y]]

本质上来说,对于list1的每个元素,我希望2个元素位于list2的第一个元素的不同索引处.

Essentially for every element of list1, I want the 2 elements at different indexes to the first element in list2.

因此,"a"表示在索引0处,其他2为"y".在索引1和"z"处在索引2处.

so for "a" at index 0, the other 2 are "y" at index 1 and "z" at index 2.

我很确定我知道如何使用索引来实现它,但是,我知道那不是很有效,所以想看看那里是否有更实用的解决方案.

I'm pretty sure I know how to do it using indexes, however, I know that that's not very efficient and wanted to see if there is a more functional solution out there.

谢谢.

推荐答案

您没有描述任何极端情况,但是可以通过以下方式获得所需的基本行为:

You haven't described any edge cases, but you can get the basic behavior you're looking for with something like:

import Data.List (inits, tails)

combine :: [a] -> [a] -> [[a]]
combine xs ys = zipWith3 go xs (tails ys) (inits ys)
  where
    go a (_:xs) ys = a:ys ++ xs
    go _ _ _ = []

关键是 tails 返回其列表的后缀(从完整列表开始),而 inits 返回连续的前缀(从空列表开始).

The key is that tails returns successive suffixes of its list starting with the full list, and inits returns successive prefixes starting with the empty list.

这篇关于Haskell在不同索引处组合了2个列表的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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