BAM Weblog

## Roy - Deep Pattern Matching

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