0

I' trying to print a types value in SML and with no success. Please take a look at the code below and let me know what do I need to do in order to fix this. Thanks.

(* Language Definition *)
datatype = Id of string;

(* Expression Definition *)
datatype expr = 
Var of ident 
| Num of int 
| Plus of expr * expr
| Paren of expr;

val p = Id "x";
val p = Var p;
print(p);

This is my error:

stdIn:175.1-175.9 Error: operator and operand don't agree [tycon mismatch]
  operator domain: string
  operand:         expr
  in expression:
    print p

I tried a lot of combination and castings but with no success.

Alexander Tilkin
  • 149
  • 1
  • 2
  • 13
  • `datatype = Id of string;` doesn't make sense - you need to give your datatype a name. Although, since you apparently get no error from this, it's probably just a mistake that happened when you typed in your code on stackoverflow? – Tayacan Nov 25 '12 at 00:36

1 Answers1

2

As the compiler is trying to say, print can only be used to print strings. If you want to be able to print your specific type, you need a printing function tailored to your datatype. Painful, I know.

Try this:

fun print_expr (Var (Id name)) = print name
    | print_expr (Num n) = print (Int.toString n)
    | print_expr (Plus (lhs, rhs)) = (print_expr lhs; print " + "; print_expr rhs)
    | print_expr (Paren e) = (print "("; print_expr e; print ")")
print_expr p;
Trillian
  • 6,207
  • 1
  • 26
  • 36