Hi,

On Wed, May 5, 2010 at 1:21 PM, <[email protected]> wrote:
>
> Given a tree, i'm trying to put on a list the values of leaf nodes only.
>

Tree traversal in functional programming language usually combines the
results of the subtrees to a single return value:

declare
fun {LeafValues T}
   case T of
   %% for a leaf, return its value as a singleton list:
   tree(value:V left:nil right:nil) then [V]
   %% an "empty node" has no values:
   [] nil then nil
   %% for other nodes, combine the leaf values of left and right children
   [] tree(left:L right:R ...) then {Append {LeafValues L} {LeafValues R}}
   end
end

Root=tree(value:a left:X1 right:X2)
X1=tree(value:b left:nil right:nil)
X2=tree(value:c left:X3 right:X4)
X3=tree(value:d left:nil right:nil)
X4=tree(value:e left:nil right:nil)

{Browse {LeafValues Root}}

Note how we can use "case" to compare the "left" and "right" fields with
"nil" and at the same time extract "value" into a variable. This is a
typical use of pattern matching.

Cheers,
  Wolfgang
_________________________________________________________________________________
mozart-users mailing list                               
[email protected]
http://www.mozart-oz.org/mailman/listinfo/mozart-users

Reply via email to