Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Would you ever write seq x x?

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?

like image 788
dspyz Avatar asked May 09 '14 17:05

dspyz


3 Answers

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.

like image 139
Dan Avatar answered Oct 25 '22 14:10

Dan


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.

like image 39
MathematicalOrchid Avatar answered Oct 25 '22 14:10

MathematicalOrchid


When you say seq a b what you are telling the computer is,

Whenever you need to evaluate b, evaluate a 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, evaluate x 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.

like image 38
kqr Avatar answered Oct 25 '22 13:10

kqr