Chapter 6: Patterns all the way down

Spring cleaning

  • let assert
  • string prefix patterns

Error(v) = problem asserts that problem is an error; if it isn't, the program crashes with a clear message. Use this when a failure would be a bug.

"Team " <> name is a string prefix pattern, right in a function head: the first clause strips the prefix, the second catches every other string.

Open in playground
pub def extract_error(problem: Result(a, b)) -> b {
  Error(v) = problem
  v
}

pub def remove_team_prefix("Team " <> name: String) -> String {
  name
}

pub def remove_team_prefix(name: String) -> String {
  name
}

pub def split_region_and_team(combined: String) -> (String, String) {
  [p1, p2] =
    combined
    |> string.split(",")

  (p1, remove_team_prefix(p2))
}

pub def main() {
  echo extract_error(Error("Not enough coffee"))
  echo remove_team_prefix("Team Turtle")
  echo split_region_and_team("East,Team Orange")
}

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