Following code has two type aliases Name
and Surname
.
Ideally I think this should not compile. Why does it compile?
Does the replacement of types happen before type-checker is involved?
import Html
type alias Name = String
type alias Surname = String
namePrinter : Name -> Name
namePrinter n =
n
k : Name
k = "kaba"
j : Surname
j = "jaja"
main =
Html.text ( "Hello!" ++ namePrinter k ++ namePrinter j )
A type alias is just that, another name for a type. It's not a different type.
You can create a distinct type by wrapping it in a custom type however:
type Name = Name String
type Surname = Surname String
But then you have to construct and deconstruct it as well:
namePrinter : Name -> String
namePrinter (Name n) =
n
k : Name
k = Name "kaba"
j : Surname
j = Surname "jaja"
And then this will fail to compile:
main =
Html.text ( "Hello!" ++ namePrinter k ++ namePrinter j )
Also, if you define this type in a separate module and don't export its constructor (ie. just Name
, instead of Name(..)
), you have what's called an opaque type which can be useful to enforce invariants that the type system cannot. You could for example enforce that an integer cannot be negative.