[Haskell-cafe] foldlWhile
Dylan Thurston
dpt at bostoncoop.net
Sat Nov 20 09:57:03 EST 2004
On Sat, Nov 20, 2004 at 03:48:23PM +0000, Jorge Adriano Aires wrote:
> > On Sat, Nov 20, 2004 at 12:47:58PM +0300, Serge D. Mechveliani wrote:
> > > 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'
> >
> > Why not just
> > foldlWhile f p a bs = takeWhile p $ foldl f a bs
>
> Quite different. The former stops a foldl when the accumulating parameter no
> longer satisfies p, the later assumes the accumulating parameter of the foldl
> is a list, and takes the portion of the list that does satisfy p.
Yes, this was a mistake.
> The following is closer to the original, but doesn't work when the whole list
> is folded (i.e., p always satisfied):
> foldlWhile f p a = head . dropWhile p . scanl f a
Serge's version returns the last 'a' that satisfies 'p', while yours
returns the first 'a' that does not satisfy 'p'. This should be an
equivalent version:
foldlWhile f p a = tail . takeWhile p . scanl f a
But what about the version with Maybe? There ought to be a concise way
to write that too.
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/3d139b35/attachment.bin
More information about the Haskell-Cafe
mailing list