You will use
pooka/int:int.parsereturnsResult(Int, ParseError)pooka/string:string.trimfor stray spaces- Guards (
if) insidematcharms
The whole program
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
- Parse, never assume.
int.parsedoes not throw. It returnsOk(number)orError(_), and the compiler makes sure you look at both. - Trim first.
" 7 "is a fine age with some air around it.string.trimlets it through. - Guards add your own rules.
Ok(age) if age < 0catches numbers that parse but make no sense. Arms are tried top to bottom, so the plainOk(age)comes after the guarded ones. - The error is a sentence.
read_agereturnsResult(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.