BAM Weblog

Roy - Simple Pattern Matching

Brian McKenna2011-06-05

This week I worked on adding simple tagged unions (sum types) and pattern matching to Roy. The diff is fairly disgusting but I'm happy that it works. Here is the example I committed:

data Maybe a =
  Some a | None

let printSomething m = match m
  case (Some x) = console.log x
  case None = console.log "Empty"

printSomething (Some 1)
printSomething None

data Either a b =
  Left a | Right b

let printString (s : String) =
  console.log s

let printResult e = match e
  case (Left x) = console.log x
  case (Right x) = printString x

printResult (Left 10)
printResult (Right "Error")

// Won't compile:
// printResult (Right 10)

data Bool =
  True | False

let getBool b ifTrue ifFalse = match b
  case True = ifTrue
  case False = ifFalse

console.log (getBool True 1 2)
console.log (getBool False 1 2)

Running the above example (with ./roy examples/data.roy && node examples/data.js) will print the following:

1
Empty
10
Error
1
2

The current version of pattern matching has no exhaustiveness check. I'll try to figure out how to do that later on.

Please enable JavaScript to view the comments powered by Disqus.