8.3 Record patterns
Record field selection can also be done through pattern matching. Standard ML has the following patterns.
{} | ||||
{,...} | ||||
The first pattern matches a record having the specified set of labels, and the second pattern matches any record containing the set of specified labels. When only a label is specified in a field then it is interpreted as a variable with the same name is specified. For example, a pattern {X, Y} is interpreted as {X = X, Y = Y}. The following are examples of field selection through record patterns.
# fun f {X = x, Y = y} = (x, y);
val f = fn : [’a, ’b. {X: ’a, Y: ’b} -> ’a * ’b]
# fun f {X = x, Y = y, ...} = (x, y);
val f = fn : [’a#{X: ’b, Y: ’c}, ’b, ’c. ’a -> ’b * ’c]
# fun f {X, Y, ...} = (X, Y);
val f = fn : [’a#{X: ’b, Y: ’c}, ’b, ’c. ’a -> ’b * ’c]
Record pattern can be freely combined with other patterns.
# fun f ({X,...}::_) = X;
val f = fn : [’a#{X: ’b}, ’b. ’a list -> ’b]
In this example, f takes a list of records containing X field, and returns the X field of the first record in the list.