Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a function that returns another function?

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?

like image 200
Julian Das Avatar asked Jan 10 '13 15:01

Julian Das


People also ask

How do you call a function that returns another function?

Approach: First call the first function-1. Define a function-2 inside the function-1. Return the call to the function-2 from the function-1.

Can I return another function in Python?

Python may return functions from functions, store functions in collections such as lists and generally treat them as you would any variable or object. Defining functions in other functions and returning functions are all possible.

How do you write a return function?

When a return statement is used in a function body, the execution of the function is stopped. If specified, a given value is returned to the function caller. For example, the following function returns the square of its argument, x , where x is a number. If the value is omitted, undefined is returned instead.

Can you reference a function in another function?

To call a function inside another function, define the inner function inside the outer function and invoke it. When using the function keyword, the function gets hoisted to the top of the scope and can be called from anywhere inside of the outer function.


1 Answers

Try this, using Python:

import math def make_cylinder_volume_func(r):     def volume(h):         return math.pi * r * r * h     return volume 

Use it like this, for example with radius=10 and height=5:

volume_radius_10 = make_cylinder_volume_func(10) volume_radius_10(5) => 1570.7963267948967 

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.

like image 107
Óscar López Avatar answered Sep 21 '22 16:09

Óscar López