I came across a pretty clever little function that takes two functions, applies one on top of each other given an argument x
:
def compose(f,g):
return lambda *x: f(g(*x))
Now my issue is with *x
, as I don't see it really doing anything here. Why couldn't it be simple x
(without the asterisk)?
Here are my tests:
>>> def compose(f,g):
... return lambda *x: f(g(*x))
...
>>> this = lambda i: i+1
>>> that = lambda b: b+1
>>> compose(this,that)(2)
4
>>> def compose(f,g):
... return lambda x: f(g(x))
...
>>> compose(this,that)(2)
4
>>> def compose(f,g):
... return lambda *x: f(g(*x))
...
>>> compose(this,that)(2,2)
TypeError: <lambda>() takes exactly 1 argument (2 given)
A lambda function evaluates an expression for a given argument. You give the function a value (argument) and then provide the operation (expression). The keyword lambda must come first. A full colon (:) separates the argument and the expression. In the example code below, x is the argument and x+x is the expression.
Lambda functions are intended as a shorthand for defining functions that can come in handy to write concise code without wasting multiple lines defining a function. They are also known as anonymous functions, since they do not have a name unless assigned one.
A lambda function can take any number of arguments, but can only have one expression.
A lambda function is an anonymous function (i.e., defined without a name) that can take any number of arguments but, unlike normal functions, evaluates and returns only one expression.
If g
(that
in your tests) can also take a variable number of arguments, then lambda *x: f(g(*x))
can be useful.
Otherwise, not so much.
The aim is to allow the composed function to be invoked with any number of arguments, and for all these arguments to be passed to the inner function in the composition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With