In Perl 5, we can apply functional programming techniques (using closures, higher order functions like map, grep, etc.). But how about function composition? Let's say, in Haskell it can be done very easily with (.) function:
map (negate . abs) [-3, 2, 4, -1, 5]
What would be the equivalent of such "dot function" in Perl?
In computer science, function composition is an act or mechanism to combine simple functions to build more complicated ones. Like the usual composition of functions in mathematics, the result of each function is passed as the argument of the next, and the result of the last one is the result of the whole.
Function composition is a way in which a function is mixed with other functions. During the composition the one function holds the reference to another function in order to fulfill it's mission.
Function composition is the way of combining two or more functions in such a way that the output of one function becomes the input of the second function and so on.
Function composition is an approach where the result of one function is passed on to the next function, which is passed to another until the final function is executed for the final result. Function compositions can be composed of any number of functions.
Sadly, I don't know Haskell.
But function composition essentially is putting the output of one function into the next function as an argument.
output = (negate . abs)(input)
is the same as output = negate(abs(input))
. In Perl, parens are often optional, and the input is implicit in the map
function, so we can just say
output = map (negate abs) list
Now just translate this to Perl syntax, and we have
my @output = map {- abs} (1,2,3);
for the mathematical/algebraic negation, and
my @output = map {! abs} (1,2,3);
for the logical negation (which is the same as map {! $_} (1,2,3)
, of course).
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