More trees
Let’s take a careful look at our in-tree
function from last time:
fun in-tree(name :: String, tree :: AncTree) -> Boolean: cases (AncTree) tree: | unknown => false | person(nm, ec, mo, fa) => (nm == name) or in-tree(name, mo) or in-tree(name, fa) end where: in-tree("George III", george-tree) is true in-tree("Sophia", george-tree) is true in-tree("Doug", george-tree) is false end
This function is recursive–it’s calling itself on the “mother” and “father” subtrees. What happens when we call:
in-tree("Friedrich II", george-tree)
(See lecture capture for details)
More tree functions
We worked through some additional functions on trees. See the lecture capture for more details about how we developed each function.
What if we wanted to find the total number of people in the tree with a particular eye color?
fun count-eye-color(color :: String, tree :: AncTree) -> Number: cases (AncTree) tree: | unknown => 0 | person(nm, ec, mo, fa) => if ec == color: 1 + count-eye-color(color, mo) + count-eye-color(color, fa) else: count-eye-color(color, mo) + count-eye-color(color, fa) end end end
Can we count the generations in the tree?
fun generations(tree :: AncTree) -> Number: cases (AncTree) tree: | unknown => 0 | person(nm, ec, mo, fa) => 1 + num-max(generations(mo), generations(fa)) end end
How about getting a list of all of the names in the tree?
fun list-names(tree :: AncTree) -> List<String>: cases (AncTree) tree: | unknown => empty | person(nm, ec, mo, fa) => link(nm, L.append(list-names(mo), list-names(fa)) end end
In what order will this produce the names in the list? What if we wanted a different order?