In Python, I'd like to write a function make_cylinder_volume(r)
which returns another function. That returned function should be callable with a parameter h
, and return the volume of a cylinder with height h
and radius r
.
I know how to return values from functions in Python, but how do I return another function?
Just want to point out that you can do this with pymonad
Try this, using Python:
Use it like this, for example with
radius=10
andheight=5
:Notice that returning a function was a simple matter of defining a new function inside the function, and returning it at the end - being careful to pass the appropriate parameters for each function. FYI, the technique of returning a function from another function is known as currying.
Using lambdas, also known as anonymous functions, you can abstract out the
volume
function inside themake_cylinder_volume_func
to a single line. In no way different from Óscar López's answer, the solution using lambda is still in a sense 'more functional'.This is how you can write the accepted answer using a lambda expression:
And then call as you'd any other curried function: