[Haskell-cafe] foldl vs foldl'

Nicolas Pouillard nicolas.pouillard at gmail.com
Wed Nov 5 08:10:23 EST 2008


Excerpts from daniel.is.fischer's message of Wed Nov 05 00:37:47 +0100 2008:
> Am Mittwoch, 5. November 2008 00:08 schrieb Daryoush Mehrtash:
> > Are there cases (function or list) where the result of foldl (or
> > foldr)would be different that foldl' (or foldr')?
> >
> > thanks,
> >
> > daryoush
> 
> Simple example:
> import Data.List
> 
> weird :: Int -> Int -> Int
> weird _ 0 = 0
> weird x y = x*y
> 
> list :: [Int]
> list = [1, 2, 3, 4, undefined, 6, 7, 8, 9, 0]
> 
> okey = foldl weird 1 list
> 
> boom = foldl' weird 1 list
> 
> *Main> okey
> 0
> *Main> boom
> *** Exception: Prelude.undefined
> 
> since foldl' evaluates strictly (to WHNF), it can die on encountering an 
> undefined value in the list where foldl doesn't.

Your example is a nice example of foldl over foldl', it would be nice to have it
in the wiki page about the different folds[1].

Best regards,

[1]: http://haskell.org/haskellwiki/Foldr_Foldl_Foldl%27

-- 
Nicolas Pouillard aka Ertai


More information about the Haskell-Cafe mailing list