What does the strictness flag do in data types?

Albert Y. C. Lai, trebla [at] vex [dot] net

In a data type definition, you can flag some parameters with ! as "strict". For example, here is a data type with two Int parameters, and the second one is flagged as strict:

data Pair = Pair Int !Int

The first parameter is evaluated lazily, as usual. This code fragment illustrates:

Pair _ m = Pair (1 `div` 0) 5
main = print m

To evaluate m, the pattern matching is carried out, which says the first parameter is unused. By lazy evaluation, unused expressions are skipped, and therefore the division by zero in the first parameter does nothing. You will get the answer 5 as expected.

The second parameter is evaluated eagerly, as requested by the ! flag. This code fragment illustrates:

Pair n _ = Pair 5 (1 `div` 0)
main = print n

To evaluate n, the pattern matching is carried out. Even though the second parameter is unused, the strictness flag it bears says evaluate anyway. The division by zero leads to an error; you will not get the answer 5.


I have more Haskell Notes and Examples