hanki

8. Pattern matching

open option
open result

struct Point
  x: i32
  y: i32
end

type LookupError
  NotFound(i32)
  Unknown
end

def show(x: i32, y: i32) -> string
  "#{x},#{y}"
end

def log(p: Point) -> string
  "point"
end
def classify!(result: Result<Point, LookupError>) -> string [Crash]
  match result
    Ok(Point(x, y)) if x > 0 -> show(x, y)
    Ok(p@_)                  -> log(p)
    Err(NotFound(id))        -> crash!("missing ##{id}")
    Err(_)                   -> crash!("unknown")
  end
end
open io

open option

def classify!(input: string, target: i32) -> string [io]
  match i32.parse(input)
    Some(guess) -> do          # do … end groups the two statements
      io.print!("checking #{guess}")
      if guess < target then "low" elif guess > target then "high" else "hit" end
    end
    None        -> "not a number"
  end
end