我正在阅读这篇文章。上面写着:
使用记录语法构造值时,如果您忘记了严格字段,GHC 会给您一个错误。它只会给你一个关于非严格字段的警告。
谁能给我一个具体的例子?
一个简单的例子:
GHCi> data Foo = Foo { bar :: !Int, baz :: String } deriving Show
bar
是严格字段,而baz
是非严格字段。首先,让我们忘记baz
:
GHCi> x = Foo { bar = 3 }
<interactive>:49:5: warning: [-Wmissing-fields]
* Fields of `Foo' not initialised: baz
* In the expression: Foo {bar = 3}
In an equation for `x': x = Foo {bar = 3}
我们收到警告,但x
是构建的。(请注意,使用 GHCi 时,默认情况下会在 GHCi 中打印警告stack ghci
。您可能需要使用:set -Wall
才能在普通 GHCi 中查看它;我不完全确定。试图在x
中使用baz
自然会给我们带来麻烦......
GHCi> x
Foo {bar = 3, baz = "*** Exception: <interactive>:49:5-19: Missing field in record construction baz
。虽然我们可以很好地达到bar
:
GHCi> bar x
3
但是,如果我们忘记了bar
,我们甚至无法首先构造值:
GHCi> y = Foo { baz = "glub" }
<interactive>:51:5: error:
* Constructor `Foo' does not have the required strict field(s): bar
* In the expression: Foo {baz = "glub"}
In an equation for `y': y = Foo {baz = "glub"}
GHCi> y
<interactive>:53:1: error: Variable not in scope: y