Skip to content

Instantly share code, notes, and snippets.

@roggenkemper
Last active Jul 21, 2022
Embed
What would you like to do?
### REVIEW ###
# Mutation
def square_tree(t):
t.label = t.label ** 2
for b in t.branches:
square_tree(b)
# New Tree
def square_tree(t):
new_branches = [square_tree(b) for b in t.branches]
return Tree(t.label ** 2, new_branches)
### Let's put it all together ###
Link(1)
Link(1, 2, 3) #should this work?
Link(1, 2) # should this work?
Link(1, Link(2)) #do i need to do this?
### String Rep ###
a = Link(1, Link(2, Link(3)))
a
print(a)
b = Link(Link(1), Link(2, Link (3)))
print(b)
### Mutation ###
a = Link(1, Link(2))
a.first = 100
a.rest.rest = a
### Linked List Range ###
def range_link(start, end):
if start >= end:
return Link.empty
return Link(start, range_link(start + 1, end))
def range_link_iter(start, end):
s = Link(start)
curr = s
start += 1
while start < end:
s.rest = Link(start)
s = s.rest
start += 1
return curr
### Map Linked List ###
def map_link(f, s):
if s is Link.empty:
return Link.empty
return Link(f(s.first), map_link(f, s.rest))
def map_link(f, s):
while s is not Link.empty:
lnk.first = f(lnk.first)
lnk = lnk.rest
### Filter Link ###
def filter(f, s):
if s is Link.empty:
return Link.empty
elif f(s.first):
return Link(s.first, filter_link(f, s.rest))
return filter_link(f, s.rest)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment