I'm not entirely clear on how seq works in Haskell.
It seems like it there are lots of cases where it would be useful to write
seq x x
and maybe even define a function:
strict x = seq x x
but such a function doesn't already exist so I'm guessing this approach is somehow wrongheaded. Could someone tell me if this is meaningful or useful?
seq a b
returns the value of b
, but makes that value depend on the evaluation of a
. Thus, seq a a
is exactly the same thing as a
.
I think the misunderstanding here is that seq
doesn't take any action, because pure functions don't take actions, it just introduces a dependency.
There is a function evaluate :: a -> IO ()
in Control.Exception
that does what you want (note that it's in IO
). They put it in exception because it's useful to see if the evaluation of an expression would throw, and if so handle the exception.
The expression x = seq a b
means that if x
is evaluated, then a
will also be evaluated (but x
will be equal to b
).
It does not mean "evaluate a
now".
Notice that if x
is being evaluated, then since x
equals b
, then b
will also be evaluated.
And hence, if I write x = seq a a
, I am saying "if x
is evaluated then evaluate a
". But if I just do x = a
, that would achieve exactly the same thing.
When you say seq a b
what you are telling the computer is,
Whenever you need to evaluate
b
, evaluatea
for me too, please.
If we replace both a
and b
with x
you can see why it's useless to write seq x x
:
Whenever you need to evaluate
x
, evaluatex
for me too, please.
Asking the computer to evaluate x
when it needs to evaluate x
is just a useless thing to do – it was going to evaluate x
anyway!
seq
does not evaluate anything – it simply tells the computer that when you need the second argument, also evaluate the first argument. Understanding this is actually really important, because it allows you to understand the behaviour of your programs much better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With