Let's say I have a n-ary tree type
type tree = Node of (char*tree) list ref;;
and this correspond to the empty tree
let empty_tree ()= Node(ref[]);;
I'm trying to write a function that only looks if my tree is empty or not, such as
let checkIsEmpty t = match t with empty_tree-> print_string "tree is empty";;
But when I write checkIsEmpty empty_tree;;
it just return a unit, it won't print "tree is empty"
I also tried that way
let checkisEmpty t = match t with z when z = empty_tree-> print_string "tree is empty";;
Sadly it still fails.
How can I look if my tree is empty? I'd like to keep the match with and the way tree is declared (Empty is not part of the type..) if possible.
Thanks!
You most likely need to flush the output to see it. You can write this:
print_string "tree is empty"; flush stdout
However, your first match doesn't work. Any identifier in a pattern introduces a new variable. So the variable empty_tree
in your first implementation will always match whatever tree you pass to your function. (Or indeed it will match any value whatsoever.)
The second implementation should work a little better once you add flush stdout
, and assuming there is a global value empty_tree
that is an empty tree. But you should also add a case that matches when the tree is not empty; otherwise you'll get an exception for that case.
Furthermore your empty_tree
is a function that returns an empty tree. It's not an empty tree itself (as your latest code is assuming).
(I would suggest you not modify your question too much after asking it. It makes it hard to write an answer that corresponds to what you asked.)