[Haskell-beginners] Re: Printing the result of a function evaluation

Stephen Blackheath [to Haskell-Beginners] mutilating.cauliflowers.stephen at blacksapphire.com
Mon Mar 8 21:02:37 EST 2010


OK - I'm with ya.  Well, 'speedTest (read $ head args) `seq` return ()'
will evaluate your expression but it'll return ().  The quick fix would
be to use 'return $! speedTest (read $ head args)' - That will also
evaluate the expression, but it'll return the output too.  The $! is the
bit that forces it the evaluation of the function (so the evaluation
happens during the bit that is timed).

Actions are evaluated just before they're sequenced in IO, and this is
actually the source of all forcing of evaluation in Haskell (or at
least, in GHC).  Doing 'x `seq` return ()' is one way to tie the
evaluation to x to IO's evaluation, and 'return $! x' is another way.  I
think the second one is equivalent to 'x `seq` return x`.  Or, in your
case it would be 'let x = speedTest (read $ head args) in x `seq` return
x', so $! saves you a bit of typing.

1. IO says 'evaluate the IO a value!' which requires the argument to be
passed to the 'return' function (but not evaluated).
2. $! says 'force evaluation of the argument, then pass it to the
function.  This causes the evaluation to be tied to IO, and therefore
actually forces the evaluation.

Clear as coffee?


Travis Erdman wrote:
> Steve, I should have provided the following details ...
> The code I pasted was a timing function I've come across in various
> Haskell literature, and it "works" as is ... at least, the timing
> results it prints are plausible.
> My sole "contribution" to the code was the "print v" line, in an attempt
> to have it print BOTH the result of the function evaluation AND the time
> it took to evaluate it (and still only evaluating the function once).
> As noted, my "print v" prints only "()" regardless of the function --
> not what I wanted.  But the timing part still works.  There has got to
> be an easy fix here, but I have yet to discover it ...
> ------------------------------------------------------------------------
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners

More information about the Beginners mailing list