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

Mar*_*ier 2 haskell strictness

我正在阅读这篇文章。它写道:

当用记录语法构造一个值时,如果你忘记了一个严格的字段,GHC 会给你一个错误。它只会对非严格字段发出警告。

谁能给我一个具体的例子?

dup*_*ode 5

一个简单的例子:

GHCi> data Foo = Foo { bar :: !Int, baz :: String } deriving Show
Run Code Online (Sandbox Code Playgroud)

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}
Run Code Online (Sandbox Code Playgroud)

我们收到警告,但x已构建。(请注意,使用 时默认会在 GHCi 中打印警告stack ghci。您可能必须使用:set -Wall普通 GHCi 来查看它;我不完全确定。)尝试使用bazinx自然会给我们带来麻烦......

GHCi> x
Foo {bar = 3, baz = "*** Exception: <interactive>:49:5-19: Missing field in record construction baz
Run Code Online (Sandbox Code Playgroud)

...虽然我们可以bar很好地达到:

GHCi> bar x
3
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)