Chapter 3: Your own types
Bandwagoner
- records
- record update
- label shorthand
A variant with named fields is a record. Coach(name:,
former_player:) uses the label shorthand: when a variable has the
same name as the field, you write the label once.
Team(team | coach:) copies team with a new
coach. It reads like Elixir's map update and compiles to Gleam's
Team(..team, coach: coach).
Fields chain with dots: team.coach.name.
pub type Coach {
Coach(
name: String,
former_player: Bool
)
}
pub type Stats {
Stats(wins: Int, losses: Int)
}
pub type Team {
Team(name: String, coach: Coach, stats: Stats)
}
def create_coach(name: String, former_player: Bool) -> Coach {
Coach(name:, former_player:)
}
def create_stats(wins: Int, losses: Int) -> Stats {
Stats(wins:, losses:)
}
def create_team(name: String, coach: Coach, stats: Stats) -> Team {
Team(name:, coach:, stats:)
}
def replace_coach(team: Team, coach: Coach) -> Team {
Team(team | coach:)
}
def is_same_team(home_team: Team, away_team: Team) -> Bool {
home_team == away_team
}
def root_for_team(team: Team) -> Bool {
cond {
team.coach.name == "Pames Jazo" -> True
team.coach.former_player -> True
team.name == "Chicago Bulls" -> True
_ -> False
}
}
pub def main() {
coach1 = create_coach("James Pazo", False)
coach2 = create_coach("Pames Jazo", False)
stats = create_stats(21, 12)
team = create_team("Lapis Panthers", coach1, stats)
new_team = replace_coach(team, coach2)
echo new_team
echo is_same_team(team, new_team)
echo root_for_team(new_team)
}pub type Coach {
Coach(name: String, former_player: Bool)
}
pub type Stats {
Stats(wins: Int, losses: Int)
}
pub type Team {
Team(name: String, coach: Coach, stats: Stats)
}
fn create_coach(name: String, former_player: Bool) -> Coach {
Coach(name: name, former_player: former_player)
}
fn create_stats(wins: Int, losses: Int) -> Stats {
Stats(wins: wins, losses: losses)
}
fn create_team(name: String, coach: Coach, stats: Stats) -> Team {
Team(name: name, coach: coach, stats: stats)
}
fn replace_coach(team: Team, coach: Coach) -> Team {
Team(..team, coach: coach)
}
fn is_same_team(home_team: Team, away_team: Team) -> Bool {
home_team == away_team
}
fn root_for_team(team: Team) -> Bool {
case team.coach.name == "Pames Jazo" {
True -> True
False ->
case team.coach.former_player {
True -> True
False ->
case team.name == "Chicago Bulls" {
True -> True
False -> False
}
}
}
}
pub fn main() {
let coach1 = create_coach("James Pazo", False)
let coach2 = create_coach("Pames Jazo", False)
let stats = create_stats(21, 12)
let team = create_team("Lapis Panthers", coach1, stats)
let new_team = replace_coach(team, coach2)
echo new_team
echo is_same_team(team, new_team)
echo root_for_team(new_team)
}src/e10_bandwagoner.bea:53
Team("Lapis Panthers", Coach("Pames Jazo", False), Stats(21, 12))
src/e10_bandwagoner.bea:55
False
src/e10_bandwagoner.bea:57
TrueAn exercism exercise from the Gleam track, solved in Bea: beacode/src/e10_bandwagoner.bea