The professor used the "Binary version of the function". Does it even exist?

Our professor used this in the assignment. I don't think the "Binary version of the function" exists after a google search. What do you think this means?

Let's say we have an add function that adds a bunch of numbers. Rather than write add (3, 5, 4, 1), we want to use currying to create an adder function that can be extended by chaining calls. Then we have an adder (3) (5) (4) (1) (). Suppose we have a currying function that can create this adder given the add2 function (the binary version of add ) and the initial value. Let's call it curry. Then we have adder = curry (add2, 0).

+3


source to share


3 answers


In this case, "binary function" refers to an argument that takes two arguments. In this case, your professor is probably referring to something like this:



def add2(x, y):
    return x + y
    # equivalently: add2 = lambda x,y: x+y

def curry(func, num):
    def wrapped(*args):
        if len(args) == 0:
            return num
        elif len(args) > 1:
            raise TypeError('{} takes 1 positional argument but '
                            '{} were given'.format(
                                func.__name__, len(args)))
        arg = args[0]
        return curry(func, func(num, arg))
    return wrapped

      

+2


source


I think it means a function that only takes two arguments, so it just adds two numbers. His example function add(3, 5, 4, 1)

would be a function that takes any number of arguments and adds all of them, but add2

only takes two arguments, so it add2(3, 5)

will be 8. "Binary version of a function" in this case means a binary function (a function that takes two arguments).



+7


source


@AdamSmith and @BrenBarn have already pointed out what binary function means . A simple and straightforward assignment solution can be written using an object instead of a decorator.

class curry():
    def __init__(self, func, default):
        self._f = func
        self._default = default
    def __call__(self, val=None):
        if val is None:
            return self._default
        return curry(self._f,self._f(self._default,val))

print(curry(lambda x,y:x+y, 0)(3)(5)(4)(1)())

      

Neat and simple!

IMHO functors should only be used when they increase readability, simplicity, or hide tedious work. In this case, the implementation of objects and functors is actually the same, but the object version is more readable and understandable.

+2


source







All Articles