12.6.3 Mapping A Composed Function

12.6.3  Mapping A Composed Function

  Now, we will write a composing function composeL that is quite similar to what we have already seen, but one which takes two lists as parameters: the first is a list of function references, and the second is a list of numbers. composeL composes the functions and maps the composed function on every element of the second list.

 Program 12.30

#funcallL is given a reference to a function and a list of   
#parameters in a list. 
#It maps the  function on the list elements and returns the result.

sub funcallL{
    my ($funRef, @parameters) = @_;
           map {funcallS ($funRef, $_)} @parameters;
}

sub composeL{
   my $firstFunction = pop @_;
   my @functions = reverse @_;

   my $composedFunction = sub{
                 my @temp = map {funcallS ($firstFunction, $_)} @_;
                 foreach $function (@functions){
                             @temp = map {funcallS ($function, $_)}  @temp;
                 };
                  return @temp;};
   return $composedFunction;
}

$add1 = sub {$_[0] + 1;};
$add2 = sub {$_[0] + 2;};
$add3 = sub {$_[0] + 3;};

Here, we define a function funcallL that maps a referenced function onto a list of parameters. It calls the funcallS function we have defined earlier.

Here is a call to composeL.

funcallL (composeL ($add1, $add2, $add3), (10, 200, 391))

composeL composes the three functions references to which are given in in the list parameter given to it. funcallL then applies the composed function to the list given as the second parameter to it.

Below we see that we can use the combination of funcallL and composeL to apply the composed function to a single parameter, which happens to be 10 here.

funcallL (composeL ($add1, $add2, $add3), 10)