Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

Suppose I had 2 lists, of equal length.

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

I want to create the list

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

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

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.

Thank you.

question from:https://stackoverflow.com/questions/66050529/haskell-combine-the-elements-of-2-lists-at-different-indexs

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
234 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 _ _ _ = []

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...