← Cookbook Basics Beginner · Pooka 0.5.0

Parse a number safely

Text from a person is a promise, not a number. Check it, and say kindly what was wrong.

You will use

  • pooka/int: int.parse returns Result(Int, ParseError)
  • pooka/string: string.trim for stray spaces
  • Guards (if) inside match arms

The whole program

src/main.pooka
module main

import pooka/int
import pooka/io
import pooka/list
import pooka/string

read_age(text: String) -> Result(Int, String) {
  match int.parse(string.trim(text)) {
    Ok(age) if age < 0 -> Error("an age cannot be negative")
    Ok(age) if age > 150 -> Error("that is a very old owl")
    Ok(age) -> Ok(age)
    Error(_) -> Error("`" + text + "` is not a whole number")
  }
}

main() {
  ["42", " 7 ", "-3", "forty", "200"]
  |> list.each(fn(text: String) {
    let line = match read_age(text) {
      Ok(age) -> "ok     " + int.to_string(age)
      Error(reason) -> "error  " + reason
    }
    io.println(line)
    Nil
  })
}

Run it

$ pooka run
ok     42
ok     7
error  an age cannot be negative
error  `forty` is not a whole number
error  that is a very old owl

How it works

  1. Parse, never assume. int.parse does not throw. It returns Ok(number) or Error(_), and the compiler makes sure you look at both.
  2. Trim first. " 7 " is a fine age with some air around it. string.trim lets it through.
  3. Guards add your own rules. Ok(age) if age < 0 catches numbers that parse but make no sense. Arms are tried top to bottom, so the plain Ok(age) comes after the guarded ones.
  4. The error is a sentence. read_age returns Result(Int, String), with a message a person can act on, not a stack trace.

Try next: float.parse works the same way for decimals. Use ? to pass a parse error straight up from a function that reads several numbers.