12.6.2 Composing A Set of Functions

12.6.2  Composing A Set of Functions

  We now write a function composeS that takes a list of function references and returns a reference to a composed function. We use the function funcallS defined earlier to apply a referenced function to a scalar parameter. Here is the composeS function.

 Program 12.29

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

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

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

 

A call to composeS looks like the following.

 

funcallS (composeS ($add1, $add2, $add3), 10)

 

We have defined three simple anonymous functions. These functions are referenced using the scalars $add1, $add2 and $add3. The functions simply add 1, 2 and 3, respectively to a scalar parameter given. The call

 

composeS ($add1, $add2, $add3)

 

composes these three functions and returns a reference to the new function. This newly created function is then called on the parameter 10 using the funcallS function. The result of the call to funcallS returns 16.

Let us now look at the definition of the composeS function. Its parameter list @_ is a list of function references. The first function reference is separated from the rest of the functions and is stored in the scalar $firstFunction. The rest of the function references are stored in @functions.

Following this, we create a local variable $composedFunction that is assigned the reference to the anonymous function composed by applying all the functions to the scalar parameter provided. This anonymous function inside the composeS function first calls $firstFunction on the scalar parameter. Then, it goes through a for loop in which each of the remaining functions referenced in @functions are applied on the result of the first function application. This anonymous function inside our main function returns the value obtained after all the referenced functions have been applied to the scalar parameter.

Finally, the composeS function returns the value of $composedFunction. In other words, composeS returns a reference to an anonymous function that calls all the composed functions on the scalar parameter. Since composeS returns a reference to a function, we have to use funcallS to apply the composed function on the scalar parameter.