Lesson 11 of 17
Custom Types
Defining Custom Types
Custom types in Gleam are sum types (also called algebraic data types or tagged unions). They let you define a type that can be one of several variants:
pub type Season {
Spring
Summer
Autumn
Winter
}
Each variant is a constructor. You create values by calling the constructor:
let current = Summer
Variants with Data
Variants can carry data:
pub type Shape {
Circle(radius: Float)
Rectangle(width: Float, height: Float)
Triangle(base: Float, height: Float)
}
You create them by passing arguments:
let s = Circle(radius: 5.0)
let r = Rectangle(width: 10.0, height: 20.0)
Matching on Custom Types
Use case to handle each variant:
fn describe(shape: Shape) -> String {
case shape {
Circle(radius: r) -> "circle with radius " <> float.to_string(r)
Rectangle(width: w, height: h) -> "rectangle " <> float.to_string(w) <> "x" <> float.to_string(h)
Triangle(..) -> "triangle"
}
}
The .. pattern ignores all fields of a variant.
The Power of Sum Types
Sum types make impossible states impossible. Consider representing a traffic light:
pub type Light {
Red
Yellow
Green
}
There is no way to create an invalid light color. The type system guarantees correctness.
Your Task
Define a Direction type with four variants: North, South, East, West. Write a function opposite that returns the opposite direction. Print the opposite of each direction.
Gleam runtime loading...
Loading...
Click "Run" to execute your code.