I'm brand new to ML and I'm trying to figure out the syntax for pattern matching.
Can someone help me understand the compiler error, and the correct syntax for pattern matching an AssignStm
while binding its second argument to the variable e
?
Maybe what I'm trying to do is simply not supported? I have an ADT defined as follows.
type id = string
datatype binop = Plus | Minus | Times | Div
datatype stm = CompoundStm of stm * stm
| AssignStm of id * exp
| PrintStm of exp list
and exp = IdExp of id
| NumExp of int
| OpExp of exp * binop * exp
| EseqExp of stm * exp
And I'm trying to implement a function which counts the number of calls to print
in a given statement.
The compiler complains
/Users/jimka/Repos/mciml/fig4.1.sml:15.60 Error: unbound variable or constructor: e
Here is my code:
fun maxints(a,b) =
if a > b then a else b
fun maxargs PrintStm nil = 0
| maxargs PrintStm h::t = 1 + (maxargs printStm t )
| maxargs CompoundStm(a,b) = maxints(maxargs a, maxargs b)
| maxargs AssignStm(_,e: exp) = maxargs e (* the error is on this line *)
| maxargs IdExp = 0
| maxargs NumExp = 0
| maxargs OpExp(e1,_,e2) = maxints(maxargs e1, maxargs e2)
| maxargs EseqExp(s,e) = maxints(maxargs s, maxargs e)
The actual code which triggers the error is the following:
val prog =
CompoundStm(AssignStm("a",OpExp(NumExp 5, Plus, NumExp e)),
CompoundStm(AssignStm("b",
EseqExp(PrintStm[IdExp"a", OpExp(IdExp"a", Minus,
NumExp 1)],
OpExp(NumExp 10, Times IdExp"a"))),
PrintStm[IdExp "b"]))
maxargs prog
molbdnilo suggested the following. But I get the same error.
fun maxargs( PrintStm nil) = 0
| maxargs( PrintStm (h::t)) = 1 + maxints(maxargs(h), maxargs( PrintStm( t )))
| maxargs( CompoundStm (a,b)) = maxints(maxargs( a), maxargs( b))
| maxargs( AssignStm (_,e)) = maxargs( e)
| maxargs( IdExp (_)) = 0
| maxargs( NumExp (_)) = 0
| maxargs( OpExp (e1,_,e2)) = maxints(maxargs e1, maxargs e2)
| maxargs( EseqExp (s,e)) = maxints( maxargs(s), maxargs(e))