Tuple bang patterns

可紊 提交于 2019-12-22 04:46:11

问题


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) = (..)?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/6509399/tuple-bang-patterns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!