Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in Elm between type and type alias?

Tags:

elm

In Elm, I can't figure out when type is the appropriate keyword vs. type alias. The documentation doesn't seem to have an explanation of this, nor can I find one in the release notes. Is this documented somewhere?

like image 899
ehdv Avatar asked Aug 24 '15 16:08

ehdv


People also ask

What is type alias key word used for in Elm?

The main benefit of using a type alias for this is when we write the type annotations for the update and view functions. Writing Msg -> Model -> Model is so much nicer than the fully expanded version! It has the added benefit that we can add fields to our model without needing to change any type annotations.

What is a type alias?

A type alias allows you to provide a new name for an existing data type into your program. After a type alias is declared, the aliased name can be used instead of the existing type throughout the program. Type alias do not create new types. They simply provide a new name to an existing type.

What is Elm type?

Advertisements. The Type System represents the different types of values supported by the language. The Type System checks validity of the supplied values, before they are stored or manipulated by the program. This ensures that the code behaves as expected.

What is type alias in Scala?

A type alias is usually used to simplify declaration for complex types, such as parameterized types or function types. Let's explore examples of those aliases and also look at some illegal implementations of type aliases.


1 Answers

How I think of it:

type is used for defining new union types:

type Thing = Something | SomethingElse 

Before this definition Something and SomethingElse didn't mean anything. Now they are both of type Thing, which we just defined.

type alias is used for giving a name to some other type that already exists:

type alias Location = { lat:Int, long:Int } 

{ lat = 5, long = 10 } has type { lat:Int, long:Int }, which was already a valid type. But now we can also say it has type Location because that is an alias for the same type.

It is worth noting that the following will compile just fine and display "thing". Even though we specify thing is a String and aliasedStringIdentity takes an AliasedString, we won't get an error that there is a type mismatch between String/AliasedString:

import Graphics.Element exposing (show)  type alias AliasedString = String  aliasedStringIdentity: AliasedString -> AliasedString aliasedStringIdentity s = s  thing : String thing = "thing"  main =   show <| aliasedStringIdentity thing 
like image 178
robertjlooby Avatar answered Oct 07 '22 10:10

robertjlooby