Elm types have 2 parts:
- The
nameof the type that starts with an uppercase character - The different
constructors
type Vehicle
= Car Int
| Truck Int Float
| Van IntHere 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 2We 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 yourCarNotice here the _ variable is used as a Don't Care since we don't care about the tons part of Truck.