[Tutor] Valid usage of lambda expression

Alan Gauld alan.gauld at yahoo.co.uk
Wed Sep 29 03:43:55 EDT 2021


> Now if  start with a function definition  like this :
> def make_powerfunction(n):
>     return lambda x: x**n
> 
> and then :
> square = make_powerfunction(2)
> cube = make_powerfunction(3)
> cuberoot = make_powerfunction(1/3)
> 
> My question is, is it a good practice to derive new functions in this way,
> 
There are two separate issues here:
1) the use of a factory function to return other functions, specifically partial functions.
2) The use of lambda

My response would be that the use of a factory function to create partial functions is fine and quite common in functional programming circles. However the use of lambda is limited to very small functions - a single expression - and the use of partial functions is often used when dealing with more complex expressions. So in practice we would normally it used like:

Def complex_func(lots,of,params):
       Stuff here

Def partial1(parm):
      Return lambda x: complex_func(parm,”1”,x)

def partial2(parm):
       Return lambda x : complex_func(1,parm,x)

Etc

Where lambda is used only to create the call to complex_func() with the right parameters but not to create the complex func itself. 

You could replace the lambda with a nested def inside the factory:

Def partial3(parm)
     Def fun(x)
           Return fun(x,”2”,parm)
     Return fun

So you can do partial functions without use of lambda, the two issues are separate.

PS. Apologies for all the uppercase letters, I’m on a tablet and the auto correct is on…

Alan G.




More information about the Tutor mailing list