[Haskell-beginners] Is there an "unscan" function?

Christian Maeder Christian.Maeder at dfki.de
Mon Jan 16 09:14:50 CET 2012


Am 13.01.2012 19:19, schrieb Stephen Tetley:
> Hi Jeffrey
>
> My version actually contains an error, it should be:
>
> unscan :: (a ->  a ->  b) ->  [a] ->  [b]
> unscan f (a:b:bs) = f a b : unscan f (b:bs)
> unscan _ _        = []
>
> A slightly less concise, but optimized version avoids putting the
> second element back in a list:
>
> unscan f (a:b:bs) = f a b : go b bs
>    where
>      go _ [] = []
>      go x (z:zs) = f x z : go z zs
> unscan _ _        = []

This version contains duplicate code: The first line could be:

   unscan f (a : bs) = go a bs

"putting the second element back" can be avoided by @-Patterns!

   unscan f (a : bs@(b : _)) = f a b : unscan bs

Cheers Christian



More information about the Beginners mailing list