Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tuple bang patterns

I understand that in:

f x = x + 1 where !y = undefined

the meaning of the bang pattern is that y is to be evaluated before f.

Similarly:

f x = x + 1 where !(!a, !b) = (undefined, undefined)

the meaning is the same, w.r.t x and y.

But what do the bang patterns mean in:

f x = x + 1 where (!a, !b) = (undefined, undefined)

It doesn't seem to cause undefined to be evaluated. When do in-tuple bang patterns come into effect? If the pattern's tuple is forced? Can anyone give an example where (!a, !b) = (..) differs from (a, b) = (..)?

like image 863
Peaker Avatar asked Jun 28 '11 15:06

Peaker


2 Answers

A bang pattern on the tuple itself will force evaluation of the tuple but not its elements. Bang patterns on the tuple elements will force them whenever the tuple itself is evaluated.

Here's an example of the differing behavior:

Prelude> let x = a + 1 where (a, b) = (1, undefined)
Prelude> x
2
Prelude> let x = a + 1 where (!a, !b) = (1, undefined)
Prelude> x
*** Exception: Prelude.undefined
like image 193
hammar Avatar answered Oct 18 '22 14:10

hammar


If you translate it to let:

f x = let (!a, !b) = (undefined, undefined) in x + 1

Here, you create a tuple containing (a, b), and when the tuple is evaluated, both a and b are.

But because the tuple is never evaluated, neither a nor b are. This is basically the same as writing:

f x = let y = undefined `seq` 4 in x + 1

Since y is never evaluated, neither is undefined.

like image 41
jaspervdj Avatar answered Oct 18 '22 14:10

jaspervdj