1.16. Pattern Matching Unions

The only way to get at the current component of a union is by pattern matching. Here is an example:
Start C++ section to tut/examples/tut118.flx[1 /1 ]
     1: include "std";
     2: union int_option =
     3:   | Some of int
     4:   | None
     5: ;
     6: 
     7: val y = Some 1;
     8: 
     9: match y with
    10:   | Some ?i =>
    11:     {
    12:       print "Some ";
    13:       print i;
    14:     }
    15:   | None =>
    16:     {
    17:       print "None";
    18:     }
    19: endmatch;
    20: endl;
    21: 
End C++ section to tut/examples/tut118.flx[1]
Notice that the value 'i' in the line
  | Some ?i =>
can be used in the handler for that case. This is how we get the 'int' out of the Some option. The 'i' is scoped so it can only be seen inside the handler for the Some case. The question mark is used to indicate a pattern variable, its type is deduced from the pattern context and match argument type.

By the way, match/endmatch is an expression. It happens in the example above that each handler is a procedure value taking a unit argument, and the match expression returns one of these values depending on the argument exprssion. Oh, and it happens that the semi-colon after the 'endmatch' keyword then executes this procedure.

It is important to note that the match expression is purely functional! It doesn't print anything, it just returns a procedure which could print something.