[Haskell-cafe] Re: Don't “accidentallyparallelize”

Dan Doel dan.doel at gmail.com
Sat Sep 5 19:57:48 EDT 2009


On Saturday 05 September 2009 9:13:50 am Gracjan Polak wrote:
> [quote]
> Indeed, if GHC was in the habit of causing the second argument of seq to be
> evaluated before the first, then a lot of people would probably be
>  surprised. eg. imagine what happens to foldl':
> 
>   foldl' f a []     = a
>   foldl' f a (x:xs) = let a' = f a x in a' `seq` foldl' f a' xs
> 
> It wouldn't do what you want at all.
> [/quote]
> 
> So... seems foldl' relies on `seq` having unstated evaluation order in GHC.
> So, what guarantees does foldl' have in turn? Semantics only or
>  operational? Shouldn't it be written using `pseq`?
> 
> Seems I have always used (this `seq` that) when I meant (this `before`
>  that). Is it time to revisit my code and use `pseq` more?
> What does Haskell' say about this?

I suppose technically, what foldl' has over foldl is that it is more readily 
subject to optimization. Each recursive call is artificially made strict in 
the accumulator, so it is legal for GHC to optimize the function by keeping 
the accumulator evaluated, instead of delaying it. When GHC is run with 
optimizations on, it does analysis on all code that tries to determine such 
things, and seq can be seen as making such analysis easier for the compiler.

This is, of course, not what really happens in GHC. What really happens is 
that the first argument to seq is evaluated before the second (which is why it 
even has the intended effect when optimizations aren't on). But that doesn't 
have to be the case, strictly speaking.

-- Dan


More information about the Haskell-Cafe mailing list