Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What programming languages have something like Haskell’s `newtype`

The Haskell programming language has a concept of newtypes: If I write newtype Foo = Foo (Bar), then a new type Foo is created that is isomorphic to Bar, i.e. there are bijective conversions between the two. Properties of this construct are:

  • The two types are completely separate (i.e. the compiler will not allow you to use one where the other is expected, without using the explicit conversions).
  • They share the same representation. In particular, the conversion functions have a run-time cost of zero and return ”the same object” on the heap.
  • Conversion is only possible between such types and cannot be mis-used, i.e. type safety is preserved.

What other programming languages provide this feature?

One example seems to be single-value-structs in C when used with record accessors/constructors only. Invalid candidates would be single-valued-structs in C when used with casts, as the casts are not checked by the compiler, or objects with a single member in Java, as these would not share the same representation.

Related questions: Does F# have 'newtype' of Haskell? (No) and Does D have 'newtype'? (not any more).

like image 831
Joachim Breitner Avatar asked Jul 11 '13 10:07

Joachim Breitner


1 Answers

Frege has this, though, unlike in Haskell there is no extra keyword. Instead, every product type with just one component is a newtype.

Example:

data Age = Age Int

Also, all langugaes that have nominal typing and allow to define a type in terms of another should have this feature. For example Oberon, Modula-2 or ADA. So after

type age = integer;      {* kindly forgive syntax errors *}

one couldn't confuse an age and some other quantity.

like image 141
Ingo Avatar answered Oct 19 '22 16:10

Ingo