I don't have an SML compiler right now, so I can't test this, but try changing balanced(n1)
to (balanced (NODE n1))
(same with balanced(n2))
.
Question
I'm doing a simple excercise for a Programming Languages class in SML, the exercise is to compute if a tree is balanced or not. The following code is what I thought would be a valid solution:
datatype IntTree = LEAF of int | NODE of (IntTree * IntTree);
fun balanced (LEAF l) = true
| balanced (NODE (LEAF l, NODE n)) = false
| balanced (NODE (NODE n1, NODE n2)) = balanced(n1) andalso balanced(n2)
| balanced (NODE (NODE n, LEAF l)) = false
| balanced (NODE (LEAF l1, LEAF l2)) = true;
However when I try to run this in the interpreter I get the following error:
stdIn:98.42-98.54 Error: operator and operand don't agree [tycon mismatch]
operator domain: IntTree
operand: IntTree * IntTree
in expression:
balanced n1
stdIn:98.63-98.75 Error: operator and operand don't agree [tycon mismatch]
operator domain: IntTree
operand: IntTree * IntTree
in expression:
balanced n2
But NODE
should be of type IntTree
, why doesn't this work?
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow