Chapter 2: Making decisions

Log levels

  • strings
  • destructuring

There is no let in Bea. m = message(log_line) binds a name, and a pattern on the left destructures: [_, message] = string.split(log_line, ": ").

That pattern could fail if the line has no ": ", so Bea emits let assert for it. When a pattern can't fail, you get a plain let. You never have to choose.

Open in playground
import gleam/string

def message(log_line: String) -> String {
  [_, message] = string.split(log_line, ": ")
  message |> string.trim()
}

def log_level(log_line: String) -> String {
  [level | _] = log_line |> string.split(": ")
  
  level
  |> string.replace("[", "")
  |> string.replace("]", "")
  |> string.lowercase()
}

def reformat(log_line: String) -> String {
  m = message(log_line)
  l = log_level(log_line)

  "#{m} (#{l})"
}

pub def main() {
  echo message("[WARNING]:  Disk almost full\r\n")
  echo log_level("[ERROR]: Invalid operation")
  echo reformat("[INFO]: Operation completed")
}

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