Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function restriction by fixing an argument

How should I make function with lesser dimensionality than the original one by fixing an argument of it:

For example I want to make successor function out of sum function as follows:

def add(x, y):
    return x + y

Now I am looking for something like this:

g = f(~, 1) which would be the successor function, i.e. g(x) = x+1.

like image 331
Cupitor Avatar asked Jun 18 '13 00:06

Cupitor


People also ask

What is it called when you pass a function as an argument?

Because functions are objects we can pass them as arguments to other functions. Functions that can accept other functions as arguments are also called higher-order functions. In the example below, a function greet is created which takes a function as an argument.

Which function can use as an argument for another function?

You can use function handles as input arguments to other functions, which are called function functions. These functions evaluate mathematical expressions over a range of values.


1 Answers

You can write your own function:

def g(y):
    return f(2, y)

Or more concisely:

g = lambda y: f(2, y)

There's also functools.partial:

import functools

def f(x, y):
    return x + y

g = functools.partial(f, 2)

You can then call it as before:

>>> g(3)
5
like image 106
Blender Avatar answered Oct 15 '22 20:10

Blender