2

我正在读这篇文章。上面写着:

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

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

4

1 回答 1

5

一个简单的例子:

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 中打印警告stack ghci。您可能必须使用:set -Wall普通 GHCi 才能看到它;我不完全确定。)尝试使用bazinx自然会给我们带来麻烦......

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
于 2018-04-08T06:45:42.387 回答