fuzion-lang.dev — The Fuzion Language Portal
JavaScript seems to be disabled. Functionality is limited.
Fuzion
•
Idioms
•
Idiom # 9: Create a Binary Tree data structure
Idiom # 9: Create a Binary Tree data structure
See
programming-idioms.org
:
Code
# a Bin_Tree_Node is a value plus left and right sub-trees # Bin_Tree_Node(T type : has_total_order, val T, left, right bin_tree T) ref is # a bin_tree is either a Bin_Tree_Node or an empty tree represented by nil # bin_tree(T type : has_total_order) : choice
is
What are effects?
Running Example
# a Bin_Tree_Node is a value plus left and right sub-trees # Bin_Tree_Node(T type : property.orderable, val T, left, right bin_tree T) ref is # add element to this tree, return resulting tree # add (v T) bin_tree T => l := if (v < val) (left .add v) else left r := if (v > val) (right.add v) else right Bin_Tree_Node val l r # print this tree # show => left.show say val right.show # a bin_tree is either a Bin_Tree_Node or an empty tree represented by nil # bin_tree(T type : property.orderable) : choice (Bin_Tree_Node T) nil is # add element to this tree, return resulting tree # add (v T) bin_tree T => match bin_tree.this nil => Bin_Tree_Node v nil nil n Bin_Tree_Node => n.add v # print this tree # show unit => match bin_tree.this nil => n Bin_Tree_Node => n.show for tree bin_tree String := nil, tree.add x x in ["dog", "elephant", "cat", "cat", "cat", "cat", "lion", "ant", "bee", "albatros", "hyena", "horse", "frog"] else tree.show
What are effects?
last changed: 2024-07-01
next: Idiom # 10: Shuffle a list