Here's a very different approach. I make no claim to increased
elegance or efficiency, though I find it fairly readable and its made
of reusable parts. (Of course that's how you always finds your own
code!)
import Prelude hiding (head,tail)
-- Some would say this is how head and tail should have been defined.
head (a:_) = Just a
head _ = Nothing
tail (_:a) = Just a
tail _ = Nothing
-- A bit like map but stops when f returns Nothing.
mapWhile f (a:b) = case f a of
Just x -> x : mapWhile f b
Nothing -> []
mapWhile f [] = []
weave [] = []
weave a = mapWhile head a ++ weave (mapWhile tail a)
On 4/10/07, Bas van Dijk <[EMAIL PROTECTED]> wrote:
Hello,
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. Right now I have:
weave :: [[a]] -> [a]
weave ll = work ll [] []
where
work ll = foldr f (\rst acc -> work (reverse rst) [] acc) ll
f [] g = \_ acc -> reverse acc
f (x:xs) g = \rst acc -> g (xs:rst) (x:acc)
However I find this definition hard to read and I'm questioning its
efficiency especially due to the 'reverse' parts (how do they impact
performance and can they be removed?)
So I'm wondering if 'weave' can be defined more "elegantly" (better
readable, shorter, more efficient, etc.)?
happy hacking,
Bas van Dijk
_______________________________________________
Haskell-Cafe mailing list
[email protected]
http://www.haskell.org/mailman/listinfo/haskell-cafe
_______________________________________________
Haskell-Cafe mailing list
[email protected]
http://www.haskell.org/mailman/listinfo/haskell-cafe