Content deleted Content added
Ocaml example of tree pattern matching |
|||
Line 63:
The creations of these functions can be automated by Haskell's data [[Record (computer science)|record]] syntax.
This [[Ocaml]] example which defines a [[Red–black_tree|red-black tree]] and a function to re-balance it after element insertion shows how to match on a more complex structure generated by a recursive data type.
<syntaxhighlight lang="ocaml">
type color = Red | Black
type 'a tree = Empty | Tree of color * 'a tree * 'a * 'a tree
let rebalance t = match t with
| Tree (Black, Tree (Red, Tree (Red, a, x, b), y, c), z, d)
| Tree (Black, Tree (Red, a, x, Tree (Red, b, y, c)), z, d)
| Tree (Black, a, x, Tree (Red, Tree (Red, b, y, c), z, d))
| Tree (Black, a, x, Tree (Red, b, y, Tree (Red, c, z, d)))
-> Tree (Red, Tree (Black, a, x, b), y, Tree (Black, c, z, d))
| _ -> t (* the 'catch-all' case if no previous pattern matches *)
</syntaxhighlight>
==Filtering data with patterns==
|