Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>For simple <code>X = Y</code> declarations, <code>type</code> is documentation; <code>newtype</code> is type checking; this is why <code>newtype</code> is compared to <code>data</code>.</p> <p>I fairly frequently use <code>newtype</code> for just the purpose you describe: ensuring that something which is stored (and often manipulated) in the same way as another type is not confused with something else. In that way it works just as a slightly more efficient <code>data</code> declaration; there's no particular reason to chose one over the other. Note that with GHC's <code>GeneralizedNewtypeDeriving</code> extension, for either you can automatically derive classes such as <code>Num</code>, allowing your temperatures or yen to be added and subtracted just as you can with the <code>Int</code>s or whatever lies beneath them. One wants to be a little bit careful with this, however; typically one doesn't multiply a temperature by another temperature!</p> <p>For an idea of how often these things are used, In one reasonably large project I'm working on right now, I have about 122 uses of <code>data</code>, 39 uses of <code>newtype</code>, and 96 uses of <code>type</code>.</p> <p>But the ratio, as far as "simple" types are concerned, is a bit closer than that demonstrates, because 32 of those 96 uses of <code>type</code> are actually aliases for function types, such as</p> <pre><code>type PlotDataGen t = PlotSeries t -&gt; [String] </code></pre> <p>You'll note two extra complexities here: first, it's actually a function type, not just a simple <code>X = Y</code> alias, and second that it's parameterized: <code>PlotDataGen</code> is a type constructor that I apply to another type to create a new type, such as <code>PlotDataGen (Int,Double)</code>. When you start doing this kind of thing, <code>type</code> is no longer just documentation, but is actually a function, though at the type level rather than the data level.</p> <p><code>newtype</code> is occasionally used where <code>type</code> can't be, such as where a recursive type definition is necessary, but I find this to be reasonably rare. So it looks like, on this particular project at least, about 40% of my "primitive" type definitions are <code>newtype</code>s and 60% are <code>type</code>s. Several of the <code>newtype</code> definitions used to be types, and were definitely converted for the exact reasons you mentioned.</p> <p>So in short, yes, this is a frequent idiom.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload