Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging two lists in Haskell

Can't figure out how to merge two lists in the following way in Haskell:

INPUT:  [1,2,3,4,5] [11,12,13,14]  OUTPUT: [1,11,2,12,3,13,4,14,5] 
like image 907
bogatyrjov Avatar asked Oct 14 '10 23:10

bogatyrjov


People also ask

What is cons in Haskell?

Internally, Haskell lists are represented as linked cons-cells. A cons-cell is like a C struct with two pointer fields head and tail. The head field points to the first element of the list, the tail field to the rest of the list.

How do you reverse a list in Haskell?

Haskell is a functional programming language where we can leverage recursion to reverse a list. This can be done by adding the first element ( x) of the list at the end of the returning list, and calling the recursive function with the list ( x s xs xs) that does not contain x.


2 Answers

I want to propose a lazier version of merge:

merge [] ys = ys merge (x:xs) ys = x:merge ys xs 

For one example use case you can check a recent SO question about lazy generation of combinations.
The version in the accepted answer is unnecessarily strict in the second argument and that's what is improved here.

like image 125
Daniel Avatar answered Sep 22 '22 05:09

Daniel


merge :: [a] -> [a] -> [a] merge xs     []     = xs merge []     ys     = ys merge (x:xs) (y:ys) = x : y : merge xs ys 
like image 25
andri Avatar answered Sep 23 '22 05:09

andri