fuzion-lang.dev — The Fuzion Language Portal
JavaScript seems to be disabled. Functionality is limited.
Fuzion
•
Idioms
•
Idiom # 16: Depth-first traversing of a binary tree
Idiom # 16: Depth-first traversing of a binary tree
See
programming-idioms.org
:
Code
traverse (f T -> unit) unit => match bin_tree.this nil => n Bin_Tree_Node => n.left.traverse f f n.val n.right.traverse f
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 # 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 # traverse this tree # traverse (f T -> unit) unit => match bin_tree.this nil => n Bin_Tree_Node => n.left.traverse f f n.val n.right.traverse f 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.traverse (s -> say s)
What are effects?
last changed: 2024-07-01
next: Idiom # 17: Create a Tree data structure