[Haskell-cafe] Weaving fun

Matthew Brecknell haskell at brecknell.org
Tue Apr 10 19:06:25 EDT 2007


Bas van Dijk:
> For my own exercise I'm writing a function 'weave' that "weaves" a
> list of lists together. For example:
> 
>   weave [[1,1,1], [2,2,2], [3,3]] ==> [1,2,3,1,2,3,1,2]
>   weave [[1,1,1], [2,2], [3,3,3]] ==> [1,2,3,1,2,3,1]
> 
> Note that 'weave' stops when a list is empty.

This *almost* does what you want:

> weave' = concat . transpose

Perhaps you could look at implementations of transpose for inspiration.
The following two sources show implementations which behave differently
when given ragged matrices. You seem to be looking for something between
these two extremes.

http://darcs.haskell.org/libraries/base/Data/List.hs
http://www.soi.city.ac.uk/~ross/papers/Applicative.html

Here's a modification of the latter to give the termination behaviour
you show above:

> weave = concat . foldr zipWeave [] where
>   zipWeave (x:xs) (ys:yss) = (x:ys) : zipWeave xs yss
>   zipWeave xs [] = map (:[]) xs
>   zipWeave [] ys = []



More information about the Haskell-Cafe mailing list