John Doe
John Doe

Reputation: 63

Haskell mix two lists

Im about to write my first haskell program, so I need your help. I want to interlink two lists. For example;

a = [4,8,20]
b = [3,5,17,56,89,30]

interlink a b = [4,3,8,5,20,17,56,89,30]

The resulting list must cointain the elements of List a and b alternately. If one List is longer then the elements of the longer list should be added to the result list after the shorter list mashed up with the elements of the longer list. I think you saw that in my example above.

Now how do i do this in Haskell??

My start

mix :: [a]->[a]->[a]
mix (x:l1) (y:l2) = (x:y:[])
mix [] [] = []

Please, can you help me??

Upvotes: 0

Views: 1579

Answers (2)

xandermonkey
xandermonkey

Reputation: 4412

I do not have an interpreter available to use as I am on a different computer to usual, but here is some code:

mix :: [a] -> [a] -> [a]
mix (x:xs) (y:ys) = x : y : mix xs ys
mix x [] = x
mix [] y = y

Edit: I just tested this online, I believe it works.

Upvotes: 2

urbanslug
urbanslug

Reputation: 146

So there are two functions transpose and concat.

-- transpose :: [[a]] -> [[a]] 
-- concat :: Foldable t => t [a] -> [a]

Since List already has an instance of Foldable this ends up being one line of code like so:

concat . transpose $ a : b : []

or

concat . transpose  $ [a,b]

The first step is to create a list of lists with transpose like so

λ> transpose  $ [a, b]
[[4,3],[8,5],[20,17],[56],[89],[30]]

which we then collapse into one.

The secret here is to use function composition. The . is a function that takes two functions and calls one after the other creating a larger function so:

(.) :: (b -> c) -> (a -> b) -> a -> c

means: take the result of the first function, transpose, and feed it to the next one, concat.

We can chain as many functions as we wish as long as the types allow it. In our case the composition creates a function [a] -> [a] -> [a]

Upvotes: 1

Related Questions