I want to make a function in standard ml that checks if a tree is complete or not, the function somehow works, but its giving me the wrong type and a warning of non-exhaustive cases
The tree code:
datatype 'data tree =
EMPTY
| NODE of 'data tree * 'data * 'data tree;
fun isComplete EMPTY = true
| isComplete (NODE(x, y, z)) = if (x = EMPTY andalso z <> EMPTY) orelse (x <> EMPTY andalso z = EMPTY) then false else true;
Now the above function’s type is: ''a tree -> bool but the required type is 'a tree -> bool
The warning I’m having is:
stdIn:169.8 Warning: calling polyEqual
stdIn:169.26 Warning: calling polyEqual
stdIn:169.45-169.47 Warning: calling polyEqual
stdIn:169.64-169.66 Warning: calling polyEqual
stdIn:124.1-169.94 Warning: match nonexhaustive
NODE (x,y,z) => ...
What is the problem I’m having?
EDIT:
Thanks to Michael, I fixed the code and now it works:
- fun isComplete EMPTY = true
| isComplete (NODE(EMPTY, _, EMPTY)) = true
| isComplete (NODE(NODE(x, y, z), _, NODE(a, b, c))) = true
| isComplete (EMPTY, _, NODE(x, y, z)) = false
| isComplete (NODE(x, y, z), _, EMPTY) = false;
The
''a tree -> booltype indicates thatais an equality type: it must be a type that supports testing with equals. Since you are using=and<>to testxandz, the tree data must support equality (even though you’re not doing anything interesting with the values). This is the root of thepolyEqualwarning.The nonexhaustive match warning is more puzzling. When I paste your datatype and function definitions into Moscow ML, I do not get a warning. I don’t think I’d worry about it too much, as I’d expect fixing the type to also take care of the warning.
To get the desired type
'a tree -> bool, I’d suggest getting rid of theifin favor of pattern matching. E.g.:I’ll leave it to you to figure out the full set of cases, as this looks like homework.
Incidentally, I don’t think your test for completeness is correct. Consider what happens when neither subtree is
EMPTY: you call the tree complete without considering the contents. This doesn’t have anything to do with the warnings you’re seeing, though.