2
votes

I'm reading this article. It reads:

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.

Can anyone give me a concrete example of this?

1

1 Answers

5
votes

A trivial example:

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

bar is a strict field, while baz is non-strict. To begin with, let's forget 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}

We get a warning, but x is constructed. (Note the warning gets printed by default in GHCi when using stack ghci. You might have to use :set -Wall to see it in plain GHCi; I'm not entirely sure.) Trying to use the baz in x naturally gets us in trouble...

GHCi> x
Foo {bar = 3, baz = "*** Exception: <interactive>:49:5-19: Missing field in record construction baz

... though we can reach bar just fine:

GHCi> bar x
3

If we forget bar, though, we can't even construct the value to begin with:

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