<< Prev | - Up - | Next >> |
Pattern matching is a very conveniant way of decomposing records. A pattern is simply a term with variables such as unit(hi:X ho:unit(Y))
. Matching a pattern agains a value means to bind the variable in the pattern to the corresponding subrecords. In Oz, we can write pattern matching as follows:
%% decomposing data structures
declare unit(hi:X ho:unit(Y)) = unit(hi:'blue'('tain') ho:unit(jazz))
{Inspect [X Y]}
The declare
is needed to declare the variables in the pattern X,Y
as new.
Pattern matching is also highly useful in conditionals. Oz provides pattern matching conditionals denoted by case ... end
beside Boolean conditionals.
Pattern matching conditionals are most typically used for defining recursive functions on recursive data structures such as lists. As an example, we consider the functional procedure SquareList
which when applied inputs a list of numbers and outputs the list its squares.
%% pattern matching conditionals and recursion
declare fun{SquareList Ints}
case Ints
of I|Is then I*I | {SquareList Is}
elseof nil then nil
end
end
{Inspect {SquareList [1 2 3 4 5]}}
{Inspect {SquareList {SquareList [1 2 3 4 5]}}}
One the one hand side, pattern matching seclects the matching condition and on the other hand side, it selects the matching data.
An implicit form of pattern matching is supported in procedure definitions. For instance, the definition of the converter function
fun{Convert [P C S]}
word(phon:[P] cat:C subcat:S)
end
we have seen before is equivalent to
fun{Convert Arg}
case Arg of [P C S] then word(phon:[P] cat:C subcat:S) end
end
<< Prev | - Up - | Next >> |