[Haskell-cafe] foldlWhile

Serge D. Mechveliani mechvel at botik.ru
Sat Nov 20 04:47:58 EST 2004


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.

Example.  Sum the list while the sum is less than bound:

  boundSum :: Integer -> [Integer] -> Integer
  boundSum    b =  
                  foldlWhile (+) (< b) 0

Example:  boundSum 100 $ map (^2) [1 ..] 

Is this reasonable? 

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


Please, copy the replies to  mechvel at botik.ru

-----------------
Serge Mechveliani
mechvel at botik.ru


       


More information about the Haskell-Cafe mailing list