Alexander Tilkin
Alexander Tilkin

Reputation: 319

Print error in SML because of types mismatch

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.

Upvotes: 0

Views: 279

Answers (1)

Trillian
Trillian

Reputation: 6437

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;

Upvotes: 2

Related Questions