lb098
lb098

Reputation: 53

Merge multiple lists

Is there a way, in haskell to merge multiple lists to one list? e.g.:

Input:

[
[0,2,0,4,0,6,0,1,0,3,0,0,0,0,0],
[0,0,3,0,0,6,0,0,2,0,0,0,0,0,1],
[0,0,0,4,0,0,0,1,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,3,0,0,0,0,1]
] 

Expected Output: [0,2,3,4,0,6,0,1,2,3,0,0,0,0,1]

Upvotes: 1

Views: 99

Answers (1)

Yuri Kovalenko
Yuri Kovalenko

Reputation: 1365

You can use transpose (you may need Data.List) to swap lines and columns of your table to simplify the processing.

Example:

[[0, 1, 0, 2, 3],
 [0, 0, 2, 0, 3]]

becomes

[[0, 0],
 [1, 0],
 [0, 2],
 [2, 0],
 [3, 3]]

Now you have a list of old columns, so you can process them one by one. For example, you could write such a function:

merge list = case dropWhile (== 0) of [] -> 0
                                      (x:_) -> x

Here we drop all leading zeros from the list, and look if the remaining list has some value, then we take it, otherwise we get 0 as a result.

Now we can use this function to process the transposed table like this:

mergeLists lists = map merge (transpose lists)

Now, we can get rid of parentheses:

mergeLists lists = map merge $ transpose lists

Or even get rid of argument (use composition):

mergeLists = map merge . transpose

Here we say, that merging lists is 1) transposing the table and 2) processing each column with merge. Each of these three versions is equivalent, so you can use any of them.

Some further reading on composition: http://learnyouahaskell.com/higher-order-functions#composition

You can see how it works here: https://repl.it/repls/ReasonablePerfectOptimization

EDIT: fixed merge to use pattern matching

Upvotes: 2

Related Questions