[Haskell-cafe] how to break foldl' ?

Malcolm Wallace Malcolm.Wallace at cs.york.ac.uk
Fri Sep 30 06:51:34 EDT 2005

> say if I want to sum a list of numbers but only until
> it hits a max limit. 
> Currently, I control it through the function and
> basically do nothing when the max is hit. However, if
> the list is very long, would this mean the same
> function would be called for the rest of the list
> which can be a waste of cycle ? In an imperative
> language, I just break/return in the middle of the
> loop.

If you are using foldl or foldl', then yes, the definition tells you
that 'foldl' itself will be applied as many times as the length of
the list:

    foldl f z []     =  z
    foldl f z (x:xs) =  foldl f (f z x) xs

For your situation, foldr is better:

    foldr f z []     =  z
    foldr f z (x:xs) =  f x (foldr f z xs)

The function 'f' is the outermost application, therefore it can decide
to ignore its second argument, meaning that the recursive call to
foldr is never computed.


More information about the Haskell-Cafe mailing list