Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty tree type in OCaml

I'm trying to create a type representing an empty binary tree (basically, only a skeleton of it). The variables of this type are then meant to be iterated over with pattern matching.

I understand how to instantiate a fixed from polymorphic variant for the standard types (int, string, etc) - see int_tree below. However, it is unclear if it is possible to make an empty variant from polymorphic one (empty_tree line below fails with SyntaxError during the compilation process).

The code is as follows:

type 'a binary_tree =                                                                                                                
  | Leaf of 'a                                                                                                                       
  | Node of 'a binary_tree * 'a * 'a binary_tree                                                                                     

type int_tree = int binary_tree;;                                                                                                    

type empty_tree = () binary_tree;;  
like image 768
soupault Avatar asked Feb 22 '26 20:02

soupault


1 Answers

() is not a type but it's the only value of the type unit.

Writing () binary_tree is like writing 0 binary_tree (instead of int binary_tree).

Your empty tree should of type unit binary_tree.

like image 128
nefas Avatar answered Feb 25 '26 13:02

nefas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!