Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to interleave two lists in Haskell in one line with higher-order functions

Tags:

haskell

I want to take two lists and return the interleaved list using one line of code.

interleave :: [a] -> [a] -> [a]
interleave xs ys = concat (zipWith (:) xs ys) 

not sure why this isn't working.

Got it:

interleave :: [a] -> [a] -> [a]
interleave xs ys = concat (zipWith (\x y -> [x]++[y]) xs ys)
like image 674
Mdomin45 Avatar asked Oct 15 '25 04:10

Mdomin45


2 Answers

You might also like

interleave xs ys = concat (transpose [xs, ys])

This is based on the observation I read ages ago (I can't remember where now -- perhaps in the Python documentation) that transposition is just an n-way zip.

like image 87
Daniel Wagner Avatar answered Oct 16 '25 22:10

Daniel Wagner


I really like this page to sort of play with the mechanics of the functions in haskell (gets your brain going also)

http://www.haskell.org/haskellwiki/Pointfree

One of the examples is:

pl \(a,b) -> a:b:[]  
uncurry ((. return) . (:))

so you can also do:

[ghci] ((. return) . (:)) 1 2
[1,2]
[ghci] concat $ zipWith ((. return) . (:)) [1..10] [11..20]
[1,11,2,12,3,13,4,14,5,15,6,16,7,17,8,18,9,19,10,20]

Daniel Wagner's is much cleaner though :)

like image 29
Charles Durham Avatar answered Oct 16 '25 23:10

Charles Durham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!