Tuesday, May 8, 2012

Recursion and Multiple Argument Functions

So in Unit 3 of CS212 at Udacity I had to create a function that takes a binary argument function as an argument and returns a function that can accept n-arguments. Let's look at it in detail.

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