hanki

8. Pattern matching

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

A binder cannot be confused with it, and there is no mistyped-constant trap: the two spellings are separate already. A pattern beginning with an uppercase letter is a constructor position, a name there that resolves to neither a constructor nor a constant is an error, and a lowercase name binds.

OP_CHAR: i32 = 0i32
OP_SET: i32 = 1i32

def op_name(op: i32) -> string
  match op
    OP_CHAR -> "char"
    OP_SET  -> "set"
    _       -> "unknown"
  end
end
open io

open result

def classify!(input: string, target: i32) -> string [io]
  match i32.parse(input)
    Ok(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
    Err(e)    -> e.reason
  end
end