4

How does this code

data D = D { _d :: ![P] } -- Note the strictness annotation!

Compare to this

newtype D = D { _d :: [P] }

An answer to a related question says:

the main difference between data and newtype is that with data is that data constructors are lazy while newtype is strict

How does this difference work when the data version has a strictness annotation?

(the question is based on real code the I've stumbled on)

yairchu
  • 23,680
  • 7
  • 69
  • 109

1 Answers1

5

For instance,

case undefined of
   D d -> "hello"

will error out for data types (strict or not strict), but will evaluate to "hello" for newtypes.

This is because, at runtime, applying a newtype constructor, or pattern matching on it corresponds to no operation. Not even forcing the value we case upon.

By contrast, pattern matching on a data constructor always forces the value we case upon.

I think this is the only runtime difference between strict data and newtype. There are some static differences, such as some GHC extensions which only affect newtype, Coercible, etc., but at runtime the two types are isomorphic (but pattern matching operates differently, as shown above).

chi
  • 111,837
  • 3
  • 133
  • 218
  • So if no such pattern matching is done, there's absolutely no difference between the two? – yairchu Nov 20 '18 at 14:28
  • 4
    There should be a slight memory overhead with the strict data that isn't there with the newtype, but I don't remember if GHC can optimize that out. – DarthFennec Nov 20 '18 at 17:33
  • 1
    @yairchu I think so. There's a small memory overhead with strict data, as DarthFennec points out. Note that "if no such pattern matching" can be a big "if" -- pattern matching is everything for data types. E.g. `case expensiveFunction 23 of D d -> ...` performs the expensive computation immediately for big data, potentially keeping in memory a long list `d` for a long time depending on the `...`. With a newtype, that list would be bound lazily, and only generated afterwards, when (and if) demanded by the `...`. – chi Nov 20 '18 at 19:33