[Haskell-cafe] Data & newtype differences. Today: strictness

Yves Parès yves.pares at gmail.com
Sun Jan 22 11:32:30 CET 2012


Hello,

I had for long thought that data and newtype were equivalent, but then I
spotted some differences when it comes to strictness.
Those can be summed up as:

data Test = Test Int

newtype TestN = TestN Int


pm (Test _) = 12  -- Strict (pm undefined = undefined)

pm2 t = t `seq` 12  -- Strict

pmN (TestN _) = 12  -- Non strict (pm undefined = 12)

pmN2 t = t `seq` 12  -- Strict


When I think about it, pm and pmN are logical, as newtype layers are
removed by the compiler and then do not exist at runtime.
Some would maybe expected pmN2 to behave just like pmN (as I don't 'seq'
the inner Int but the outer TestN), but if you follow the same logic (TestN
layer doesn't exist at runtime), then you ask to evaluate the inner Int.
This can however be misleading when you use an opaque type, can't it? As
you don't know if it's declared using data or newtype...

These make me think that pattern matching against a newtype is always lazy
(irrefutable). Am I right?

Is there some litterature expliciting in a less empiric way than I did the
differences like this between data and newtype? I've never come against
such documentation through all my learning of Haskell, yet I think it's an
important point.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20120122/9d8750d5/attachment.htm>


More information about the Haskell-Cafe mailing list