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)
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.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With