reset password
Author Message
dvariya
Posts: 3
Posted 12:47 Feb 10, 2019 |

In haskell, if we create following function with name 'myOperation'

myOperation f x y = x `f` y

e.g.

myOperation (+)  10 1 gives 11

myOperation (\x y -> x^2+y^2)  10 1 gives 101.

Could anyone help me to achieve same thing in python?
I want to understand how a function (in built or user defined) can be passed and used in python.

Thanks in advance.

gchan10
Posts: 27
Posted 12:56 Feb 10, 2019 |

I believe that you can assign a function to a variable and then pass the variable into the function parameter. Inside the function you would then use the variable as the function you passed in as normal. Correct me if I'm wrong.

jpatel77
Posts: 44
Posted 12:57 Feb 10, 2019 |

You can use lambda.

For the same example, python version:

def myOperation(f, a, b):
    return f(a, b)

print(myOperation((lambda a, b: a**2 + b**2), 10, 1))

Last edited by jpatel77 at 12:59 Feb 10, 2019.
avarg116
Posts: 8
Posted 13:00 Feb 10, 2019 |

If you would like to be able to pass a function as a parameter in Python you can just specify like so:

def myFunction(f, otherParams):

I would recommend using Callable from the typing module:

from typing import Callable

then your types in the function definition would look like so:

Note: I am using Any from here: from typing import Any

def myFunction(f: Callable, a: Any, b: Any) -> Any:

    return f(a, b)

You can further specify the type by specifying params in the passed in function:

def myFunction(f: Callable[[Any,Any], Any], a: Any, b: Any) -> Any:

    return f(a, b)

Here f: Callable[[Any,Any], Any] represents a function that takes in two parameters of Any type and produces a result of Any type

If more specific types are needed, just replace Any with the needed type.

Thanks,

Austin Vargason

rabbott
Posts: 1649
Posted 15:09 Feb 10, 2019 |

Very good!

You can also create type variables. Extending Austin's answer:

from Typing import TypeVar

T1 = TypeVar('T1')

T2 = TypeVar('T2')

T3 = TypeVar('T3')

Then you can give your function parameters and return type their own types. 

def myFunction(f: Callable[[T1, T2], T3], a: T1, b: T2) -> T3:

    return f(a, b)