Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function composition in Perl

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?

like image 753
sigidagi Avatar asked Aug 20 '12 12:08

sigidagi


People also ask

What is function composition in functional programming?

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.

What is function composition in Scala?

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.

What is composition in function in Python?

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.

What is function composition in Javascript?

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.


1 Answers

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).

like image 150
amon Avatar answered Oct 26 '22 06:10

amon