Foldl as foldr
Revision as of 21:42, 16 February 2009 by Lemming
When you wonder whether to choose foldl or foldr you may remember,that both
can be expressed as
may lean so far right it came back left again.) The converse is not true, since
may work on infinite lists, which
variants never can do.
foldl :: (a -> b -> a) -> a -> [b] -> a foldl f a bs = foldr (\b g x -> g (f x b)) id bs a
Now the question are:
- How can someone find a convolved expression like this?
- How can we benefit from this rewrite?
The answer to the second question is:We can write a
that may stop before reaching the end of the input list
and thus may also terminate on infinite input.