Search code examples
smlml

Standard ML static errors


I have to write a function that computes this datatype :

datatype Expr = X
| Y
| Avg of Expr * Expr
| Mul of Expr * Expr;

and I cannot find the error in the following funtion;

val rec compute =>  fn X => (fn x => fn y => x)
|  Y => (fn x => fn y => x)
|  Avg (e1, e2) => (fn x => fn y => (compute(e1 x y) + compute(e2 x y) div 2))
|  Mul (e1, e2) => (fn x => fn y => (compute(e1 x y) * compute(e2 x y)));

What's wrong with that?!

Any help please?


Solution

  • First, you have a syntax error: the first => should be a = (part of the val declaration).

    Second, you are putting the parentheses in the recursive calls to compute wrong: you are calling it with a single argument (which would be the result of applying e.g. e1 to the two arguments x and y).

    Here is a form that should work:

    val rec compute =
      fn X => fn x => fn y => x
      |  Y => fn x => fn y => x  (* you probably meant y? *)
      |  Avg (e1, e2) => fn x => fn y => compute e1 x y + compute e2 x y div 2
      |  Mul (e1, e2) => fn x => fn y => compute e1 x y * compute e2 x y
    

    It becomes a bit nicer if you use the syntactic abbreviation that is the fun syntax:

    fun compute X x y = x
      | compute Y x y = y
      | compute (Avg (e1, e2)) x y = compute e1 x y + compute e2 x y div 2
      | compute (Mul (e1, e2)) x y = compute e1 x y * compute e2 x y
    

    That is a (mostly) equivalent definition.