HaxeDoc2

(やまだぃちぅ) #1

1 var myTree = Node(Leaf("foo"),
2 Node(Leaf("bar"), Leaf("foobar")));
3 var match = switch(myTree){
4 // matches any Leaf
5 case Leaf(): " 0 ";
6 // matches any Node that hasr = Leaf
7 case Node(
, Leaf()): " 1 ";
8 // matches any Node that hashas
9 // r = another Node, whichhas
10 // l = Leaf("bar")
11 case Node(
, Node(Leaf("bar"), )): " 2 ";
12 // matches anything
13 case
: " 3 ";
14 }
15 trace(match); // 2


The pattern matcher will check each case from top to bottom and pick the first one that
matches the input value. The following manual interpretation of each case rule helps under-
standing the process:

case Leaf(_):matching fails becausemyTreeis aNode

case Node(_, Leaf(_)):matching fails because the right sub-tree ofmyTreeis not aLeaf,
but anotherNode

case Node(_, Node(Leaf("bar"), _)): matching succeeds

case _: this is not checked here because the previous line matched

6.4.3 Variable capture...................................


It is possible to catch any value of a sub-pattern by matching it against an identifier:
1 var myTree = Node(Leaf("foo"),
2 Node(Leaf("bar"), Leaf("foobar")));
3 var name = switch(myTree){
4 case Leaf(s): s;
5 case Node(Leaf(s), _): s;
6 case _: "none";
7 }
8 trace(name); // foo
This would return one of the following:


  • IfmyTreeis aLeaf, its name is returned.

  • IfmyTreeis aNodewhose left sub-tree is aLeaf, its name is returned (this will apply here,
    returning"foo").

  • Otherwise"none"is returned.


It is also possible to use = to capture values which are further matched:
1 var node = switch(myTree){
2 case Node(leafNode = Leaf("foo"), _):
3 leafNode;
Free download pdf