Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Classic functional approach to iteration:
- #
- # "for" and "while" keywords are superfluous when
- # recursion is supported. With the proviso that the
- # interpreter/compiler must be able to internally
- # convert tail-recursive calls to iteration to
- # prevent stack overflow.
- #
- # Python interpretor does not, so this is mostly
- # a syntactic exploration rather than a practical one.
- #
- # It does have one other benefit in that thinking about
- # writing functions without the use of iterator keywords
- # provides good practice for thinking "recursively."
- #
- # Use Case: The Robot Simulation
- #
- # The robot is trying to get home - OK, I should have
- # maybe called this "E.T. Simulation" but I'm avoiding
- # the potential copyright infringment...
- #
- # The robot starts at the upper left of an n*n grid
- # containing obstacles. It's objective is to get
- # home by a combination of walk right/down moves.
- #
- def iterate(a):
- i = 0
- n = len(a)
- def iterator():
- nonlocal i
- if i == n:
- return False
- v = a[i]
- i += 1
- return v
- return iterator
- def dowhile(proc,iter):
- v = iter()
- if v:
- proc(v)
- dowhile(proc,iter)
- def apply(f,iter):
- r = []
- dowhile(lambda v: r.append(f(v)),iter)
- return r
- a = [1,2,3,4,5,6,7,8,9]
- squarev = lambda v: v*v
- squares = apply(squarev,iterate(a))
- print(squares)
- # Robot simulation:
- # Robot finds path through obstacles to home
- # walking only right or down on the grid.
- #
- # For fun: extend this to include moves in
- # any direction.
- #
- # 0 1 2 3 4
- # 0 R _ X _ _
- # 1 _ X _ _ _
- # 2 _ _ _ _ _
- # 3 _ _ _ X H
- # 4 _ X _ _ _
- #
- def robot(gridsize,obstacles,homespot):
- path = []
- def outofbounds(coord):
- return coord > gridsize - 1
- def ishome(pos):
- return pos == homespot
- def isblocked(pos):
- return True in apply(lambda x: x == pos,iterate(obstacles))
- def walk(pos,athome,lvl):
- print(f"{' '*lvl}{pos} {home}")
- path.append(pos) # add possible pos to path
- if ishome(pos):
- return True
- r,c = pos[0],pos[1]
- if not athome and not outofbounds(r+1) and not isblocked((r+1,c)):
- athome = walk((r+1,c),athome,lvl+1)
- if not athome and not outofbounds(c+1) and not isblocked((r,c+1)):
- athome = walk((r, c+1),athome,lvl+1)
- if not athome:
- path.pop() # remove attempted pos
- return athome
- pos = (0,0)
- if not isblocked(pos):
- walk(pos,False,0)
- return path
- print("Path Home:")
- obstacles = [(0, 2),(1, 1), (3, 3), (4, 1)]
- gridsize = 5
- home = (3,4)
- path = robot(gridsize=gridsize,obstacles=obstacles,homespot=home)
- print(path)
Add Comment
Please, Sign In to add comment