Skip to content

Instantly share code, notes, and snippets.

@cscalfani
Last active July 25, 2016 22:03
Show Gist options
  • Save cscalfani/1509934abebca99062584ee8fcd31ae0 to your computer and use it in GitHub Desktop.
Save cscalfani/1509934abebca99062584ee8fcd31ae0 to your computer and use it in GitHub Desktop.
How to Think About Types in Elm

Union Types in Elm

Elm types have 2 parts:

  1. The name of the type that starts with an uppercase character
  2. The different constructors
type Vehicle
	= Car Int
	| Truck Int Float
	| Van Int

Here the type is Vehicle and the constructor for a Car takes 1 parameter of type Int.

It's called a Union Type because it's a type that can take on many different forms.

We can instantiate a car using the Car constructor as follows:

makeCar : Int -> Car
makeCar doors =
	Car doors

myCar : Car
myCar = makeCar 4

yourCar : Car
yourCar = Car 2

We can instantiate a truck using the Truck constructor as follows:

makeTruck : Int -> Float -> Truck
makeTruck doors tons =
	Truck doors tons

myTruck : Truck
myTruck = makeTruck 2 1

yourTruck : Truck
yourTruck = Truck 4 (3/4)

And then we can use myCar or yourTruck anywhere a Vehicle is called for:

doors : Vehicle -> Int
doors vehicle =
	case vehicle of
		Car doors ->
			doors
		Truck doors _ ->
			doors
		Van doors ->
			doors

myDoors : Int
myDoors =
	doors myCar

yourDoors : Int
yourDoors =
	doors yourCar

Notice here the _ variable is used as a Don't Care since we don't care about the tons part of Truck.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment