SML# Document Version 4.1.0
8 SML# feature: record polymorphism

8.3 Record patterns

Record field selection can also be done through pattern matching. Standard ML has the following patterns.

pat  ::=
 | {field_list}
 | {field_list,...}
field  ::= l=pat|l

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.