Chapter 3: Your own types

Valentine's day

  • custom types
  • case
  • guards

pub type Activity { … } defines a custom type: a value is exactly one of its variants, and some variants carry data, like Movie(Genre) or Walk(Int).

case takes them apart. Patterns nest (Movie(Romance)), guards refine them (Walk(k) if k > 11), and the compiler checks that every possibility is handled.

Open in playground
import gleam/list

pub type Approval {
  Yes
  No
  Maybe
}

pub type Cuisine {
  Korean
  Turkish
}

pub type Genre {
  Crime
  Horror
  Romance
  Thriller
}

pub type Activity {
  BoardGame
  Chill
  Movie(Genre)
  Restaurant(Cuisine)
  Walk(Int)
}

def rate_activity(activity: Activity) -> Approval {
  case activity {
    BoardGame -> No
    Chill -> No
    Movie(Romance) -> Yes
    Movie(_) -> No
    Restaurant(Korean) -> Yes
    Restaurant(Turkish) -> Maybe
    Walk(k) if k > 11 -> Yes
    Walk(k) if k > 6 -> Maybe
    Walk(_) -> No
  }
}
def do_rate(items: List(Activity), acc: List(Approval)) -> List(Approval)

def do_rate([], acc) {
  acc |> list.reverse()
}

def do_rate([head | tail], acc) {
  acc = [rate_activity(head) | acc]
  do_rate(tail, acc)
}

pub def main() {
  items = [Walk(12), Chill, Movie(Horror)]
  echo do_rate(items, [])
}

An exercism exercise from the Gleam track, solved in Bea: beacode/src/e9_valentines_day.bea