How is Haskell seq used?

Thus, the Haskell seq function forces to evaluate its first parameter and returns the third. Therefore, this is an infix operator. If you want to force an expression to be evaluated, intuitively, such a function will be a unary operator. So instead

seq :: a -> b -> b 

it will be

 seq :: a -> a 

Therefore, if the required value is a , why return b and how do you create to return b . Clearly, I do not think Haskell. :)

+6
source share
1 answer

The way to think about a `seq` b is not that it" evaluates a ", but that it creates a relationship between a and b , so when you go to evaluate b , you evaluate a .

This means, for example, that a `seq` a completely redundant: you say that Haskell evaluates a when evaluating a . By the same logic, seq a with one argument will not be different from just writing a by itself.

Just having seq a that somehow evaluates a will not work. The problem is that seq a itself is an expression that cannot be evaluated, for example, it can be deep inside some nested tricks. Thus, it will become relevant only when you get an estimate of the whole expression seq a - at what point would you still evaluate a .

@Rhymoid an example of how it is used in a strict fold ( foldl' ) is good. Our goal is to write such a fold that its intermediate accumulated value ( acc ) is fully evaluated at every step, as soon as we evaluate the final result. This is done by adding seq between the accumulated value and the recursive call:

 foldl' fz (x:xs) = let z' = fzx in z' `seq` foldl' fz' xs 

You can visualize this as a long seq chain between each application f in the fold, connecting them all with the final result. Thus, when you evaluate the final expression (i.e., the Number you get by summing the list), it strictly evaluates the intermediate values ​​(i.e., Partial sums that add up to the list).

+15
source

All Articles