BAM Weblog

Roy - Deep Pattern Matching

Brian McKenna — 2011-10-09

Roy now has deep pattern matching. That means you can write things like:

let xor e = match e
  case (Left (Left n)) = 0
  case (Left (Right n)) = n
  case (Right (Left n)) = n
  case (Right (Right n)) = 0

console.log (xor (Left (Left 100)))
console.log (xor (Left (Right 100)))
console.log (xor (Right (Left 100)))
console.log (xor (Right (Right 100)))

Which wil output:

0
100
100
0

Here’s some code I wrote while trying to break it:

let x a = match a
  case (Some (Some (Some s))) = s
  case (Some (Some None)) = 0
  case (Some None) = 0
  case None = 0

// Doesn't compile:
// console.log (x (Some (Some (Some None))))

console.log (x (Some (Some (Some 42))))
console.log (x (Some (Some None)))
console.log (x (Some None))
console.log (x None)


data Tuple a b c = Tuple2 a b | Tuple3 a b c

let addTuple t = match t
  case (Tuple3 a (Tuple3 b c d) e) = b + c + d
  case (Tuple3 a (Tuple2 b c) d) = b + c
  case (Tuple2 a (Tuple3 b c d)) = b + c + d
  case (Tuple2 a (Tuple2 b c) d) = b + c

console.log (addTuple (Tuple3 "addTuple" (Tuple2 1 2) "addTuple"))
console.log (addTuple (Tuple3 "addTuple" (Tuple3 1 2 3) "adsf"))
console.log (addTuple (Tuple2 "addTuple" (Tuple2 1 2)))
console.log (addTuple (Tuple2 "addTuple" (Tuple3 1 2 3)))

Both functions broke the type checking but now work.

I’ve been working on just deep matching for the past week. I really need to start proving parts of Roy’s type system instead of just writing it in JavaScript and hoping it works (and makes sense).

Please enable JavaScript to view the comments powered by Disqus.