缺少严格字段的​​ GHC 错误

GHC error for missing strict fields

我正在阅读 this article。上面写着:

When constructing a value with record syntax, GHC will give you an error if you forget a strict field. It will only give you a warning for non-strict fields.

任何人都可以给我一个具体的例子吗?

一个简单的例子:

GHCi> data Foo = Foo { bar :: !Int, baz :: String } deriving Show

bar是严格字段,而baz是non-strict。首先,让我们忘记 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 已构建。 (请注意,当使用 stack ghci 时,默认情况下会在 GHCi 中打印警告。您可能必须使用 :set -Wall 才能在普通 GHCi 中看到它;我不完全确定。)尝试使用 bazx 自然会给我们带来麻烦...

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