Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell - alternating elements from two lists

I'm trying to write a haskell function that takes in two lists of integers and generates a list with elements that have been taken alternatingly from the two lists.

I have the function:

blend xs ys

An example:

blend [1,2,3] [4,5,6]

should return

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

My logic is to zip the two lists together, generating the pairs of alternate elements, then somehow remove them from their tuples.

It's removing them from their tuples that I can't figure out how to implement.

like image 432
Shabu Avatar asked Dec 12 '11 06:12

Shabu


2 Answers

How about exchanging the arguments during recursion-descend?

blend (x:xs) ys = x:(blend ys xs)
blend _ _ = []

You can even generalise this approach for any number of lists (I'll leave this to you) or take the remaining elements of a list if the other is empty:

blend _ ys = ys
like image 87
bitmask Avatar answered Sep 21 '22 21:09

bitmask


If you want to zip, generate lists instead of tuples:

concat $ zipWith (\x y -> [x,y]) [1,2,3] [4,5,6]

Some pointless fun:

concat $ zipWith ((flip(:)).(:[])) [1,2,3] [4,5,6]  

Probably the easiest way:

import Data.List
concat $ transpose [[1,2,3],[4,5,6]]
like image 32
Landei Avatar answered Sep 20 '22 21:09

Landei