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? 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:
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:
I would recommend using Callable from the typing module:
then your types in the function definition would look like so: Note: I am using Any from here:
You can further specify the type by specifying params in the passed in function:
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:
Then you can give your function parameters and return type their own types.
|