The original function:
def herp(x,y):return x, y
The converting function that returns a new function:
def n_ary(f):
"""Given binary function f(x, y), return an n_ary function such
that f(x, y, z) = f(x, f(y,z)), etc. Also allow f(x) = x."""
def n_ary_f(x, *args):
return x if not args else f(x, n_ary_f(*args))
return n_ary_f
So the following can be done:
herp_n = n_ary(herp)
herp_n(1)
herp_n(1,2)
herp_n(1,2,3)
herp_n(1,2,3,4)
Recursion has sometimes been a difficult thing for me to get the hang of. I understand perfectly how it works, but when faced with a problem where it could be used I still struggle with figuring out how to implement it. This was good practice in that regards.
No comments:
Post a Comment