Pergunta

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?

Foi útil?

Solução

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.

Outras dicas

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, 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.

seq x x would be entirely, trivially redundant.

Remember, seq is not a command. The presence of a seq a b in your program does not force evaluation of a or b What it does do, is it makes the evaluation of the result artificially dependent on the evaluation of a, even though the result itself is b If you print out seq a b, a will be evaluated and its result discarded.. Since x already depends on itself, seq x x is silly.

Close! deepseq (which is the "more thorough" seq -- see the docs for a full description) has the type NFData a => a -> b -> b, and force (with type NFData a => a -> a) is defined simply as

force :: (NFData a) => a -> a
force x = x `deepseq` x
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top