Note that there are some explanatory texts on larger screens.

plurals
  1. POWithin Scala, is it possible to alias a type but disallow cross-use of aliased/non-aliased types like Haskell?
    primarykey
    data
    text
    <p>In Haskell, I believe that it is possible to alias a type in such a way that the compiler does not allow references between the aliased type and the unaliased type. According to <a href="https://stackoverflow.com/questions/2649305/why-is-there-data-and-newtype-in-haskell">this stack overflow question</a>, one can use Haskell's <code>newtype</code> like so:</p> <pre><code>newtype Feet = Feet Double newtype Cm = Cm Double </code></pre> <p>where <code>Feet</code> and <code>Cm</code> will behave like Double values, but attempting to multiply a <code>Feet</code> value and a <code>Cm</code> value will result in a compiler error.</p> <p>EDIT: Ben pointed out in the comments that this above definition in Haskell is insufficient. <code>Feet</code> and <code>Cm</code> will be new types, on which there will be no functions defined. Doing a bit more research, I found that the following will work:</p> <pre><code>newtype Feet = Feet Double deriving (Num) newtype Cm = Cm Double deriving (Num) </code></pre> <p>This creates a new type that derives from the existing <code>Num</code> type (requires using switch: <code>-XGeneralizedNewtypeDeriving</code>). Of course, these new types will be even more valuable deriving from other types such as <code>Show</code>, <code>Eq</code>, etc. but this is the minimum required to correctly evaluate <code>Cm 7 * Cm 9</code>.</p> <p>Both Haskell and Scala have <code>type</code>, which simply aliases an existing type and allows nonsensical code such as this example in Scala:</p> <pre><code>type Feet = Double type Cm = Double val widthInFeet: Feet = 1.0 val widthInCm: Cm = 30.48 val nonsense = widthInFeet * widthInCm def getWidthInFeet: Feet = widthInCm </code></pre> <p>Does Scala have a <code>newtype</code> equivalent, assuming that this does what I think it does?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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