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]
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.
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.
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.
merge :: [a] -> [a] -> [a] merge xs [] = xs merge [] ys = ys merge (x:xs) (y:ys) = x : y : merge xs ys
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