【问题标题】:GHC error for missing strict fields缺少严格字段的​​ GHC 错误
【发布时间】:2018-04-08 06:25:39
【问题描述】:

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

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

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

【问题讨论】:

    标签: haskell strictness


    【解决方案1】:

    一个简单的例子:

    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 已构建。 (注意,使用stack ghci 时,默认情况下会在 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多