CS152, Spring 2011, Assignment 2
Due: Thursday 24 February 2011, 10:00AM
Last updated: February 8
Ensure you understand the course policies for assignments.
hw2.tar
, available on the course website, contains several Caml ﬁles you need.
This assignment considers a small “language” for MLstyle pattern matching with some twists. A “program”
is a pattern
p
and a value
v
. If
p
“matches”
v
, then the result is a list of bindings
b
. Else there is no result.
Syntax deﬁnition:
v
::=
c

(
v,v
)

s
(
v
)
p
::=

x

c

(
p,p
)

s
(
p
)

...
(
p
)
b
::=
· 
(
x,v
)
,b
(
c
∈
{
0
,
1
,
2
,...
}
)
(
s
any nonempty string of English letters)
(
x
any nonempty string of English letters)
Values includes constants, pairs, and tagged values. The tag is any string (unlike in ML where type deﬁnitions
must introduce constructors). Patterns include wildcard, variables, constants, pairs, tagged patterns, and
the “descendent” pattern
...
(
p
).
Informal semantics:
•
Pattern
matches every value and produces the empty list of bindings (
·
).
•
Pattern
x
matches every value and produces the oneelement binding list (
x,v
)
,
·
when matched with
v
. Note
x
can be any variable.
•
Pattern
c
matches only the value that is the same constant and produces the empty list of bindings.
•
Pattern (
p
1
,p
2
) matches only pairs of values and only if
p
1
and
p
2
match the corresponding components
of the pair. The result is the two binding lists from the nested matches appended together.
•
Pattern
s
(
p
) matches only a tagged value where the tag is the same (i.e., the same string
s
) and
p
matches the corresponding value. The result is the result of the nested match.
•
Pattern
...
(
p
) matches a value
v
if
p
matches any descendent of
v
in the abstract syntax tree,
including
v
itself
. Put another (very useful) way, it matches if
p
matches
v
or
...
(
p
) matches a child of
v
in the
syntax tree. The result is the result of (any) successful match.
•
Assume a pattern does not have any variable more than once; you do not need to check for this.