devoured elysium
devoured elysium

Reputation: 105077

Iterating along 2 lists at the same time in haskell (without resorting to zip)

I have 2 lists:

[[1,2],[4,5]]

and

[0, 3]

and I'd like to turn it into

[[0,1,2],[3,4,5]]

I've created a function that does just that:

myFun xxs xs = map (\x -> (fst x):(snd x)) (zip xs xxs)

and it works. But I am still left wondering whether there might exist a better way to accomplish this without using the zip. Is there any?

Basically what I want to do is iterate along the 2 lists at the same time, something that I can't think of a way to do in Haskell without resorting to zip.

Thanks

Upvotes: 1

Views: 3159

Answers (3)

Yacoby
Yacoby

Reputation: 55445

Use zipWith. For example:

zipWith (:) [0,3] [[1,2],[4,5]]

Gives:

[[0,1,2],[3,4,5]]

Upvotes: 7

Anthony
Anthony

Reputation: 3791

You can move the zip into the type with ZipList from Control.Applicative:

myFun xxs xs = getZipList $ (:) <$> ZipList xs <*> ZipList xxs

Upvotes: 4

Anon.
Anon.

Reputation: 59983

Why is zip not an option?

Or should I say, zipWith.

zipWith (\x y -> x:y) xs xxs

Upvotes: 5

Related Questions