More trees, Python translation
Tree function evaluation
Let’s think a bit about how tree functions evaluate. We’ll start with this funciton we wrote last time:
data AncTree: | person(name :: String, eye-color :: String, mother :: AncTree, father :: AncTree) end george-tree = person("George III", "green", person("Auguste", "green", person("Magdalena", "blue", person("Sophia", "green", unknown, unknown), unknown), person("Friedrich II", "brown", unknown, unknown)), person("Frederick", "green", unknown, unknown)) 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
What happens if we evaluate it on george-tree
?
See the lecture capture for details.
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
Translating to Python
We did some exercises on translating Pyret to Python. Here’s the Pyret code:
fun add-shipping(subtotal :: Number) -> Number: doc: "add shipping amount to subtotal" if subtotal <= 50: subtotal + 10 else if (subtotal > 50) and (subtotal <= 100): 20 else: 30 end where: add-shipping(1) is 1 + 10 add-shipping(50) is 50 + 10 add-shipping(50.01) is 50.01 + 20 add-shipping(100) is 100 + 20 add-shipping(100.01) is 100.01 + 30 add-shipping(200) is 200 + 30 end fun register(courses :: List<String>, course :: String) -> List<String>: link(course, courses) end
And here’s the Python:
def add_shipping(subtotal: int) -> int: """add shipping amount to subtotal""" if subtotal <= 50: return subtotal + 10 elif subtotal > 50 and subtotal <= 100: return subtotal + 20 else: return subtotal + 30 def register(reg_list: list, course: str): """add the course to the reg_list""" reg_list.append(course)
Again, please see the lecture capture for more details.