[Haskell-cafe] foldlWhile

Dylan Thurston dpt at lotus.bostoncoop.net
Sat Nov 20 08:40:37 EST 2004


On Sat, Nov 20, 2004 at 12:47:58PM +0300, Serge D. Mechveliani wrote:
> Is such a function familia to the Haskell users?
> 
>   foldlWhile :: (a -> b -> a) -> (a -> Bool) -> a -> [b] -> a
>   foldlWhile    f                p              a    bs  =
>     case
>         (bs, p a)
>     of
>     ([],    _    ) -> a
>     (_,     False) -> a
>     (b:bs', _    ) -> foldlWhile f p (f a b) bs'
> 
> foldl  does not seem to cover this.

Why not just

  foldlWhile f p a bs = takeWhile p $ foldl f a bs

?

> More `generic' variant:
> 
>   foldlWhileJust :: (a -> b -> Maybe a) -> a -> [b] -> a 
>   foldlWhileJust    f                      a    bs  =  case bs of
> 
>            []    -> a
>            b:bs' -> case f a b of Just a' -> foldlWhileJust f a' bs'
>                                   _       -> a

I don't know a short way to rewrite this one yet.

Peace,
	Dylan
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url : http://www.haskell.org//pipermail/haskell-cafe/attachments/20041120/a5249de7/attachment.bin


More information about the Haskell-Cafe mailing list