Higher Order Functions


Advertisements

A higher order function (HOF) is a function that follows at least one of the following conditions −

  • Takes on or more functions as argument
  • Returns a function as its result

HOF in PHP

The following example shows how to write a higher order function in PHP, which is an object-oriented programming language −

<?php  
$twice = function($f, $v) { 
   return $f($f($v)); 
};  

$f = function($v) { 
   return $v + 3; 
}; 

echo($twice($f, 7));

It will produce the following output −

13

HOF in Python

The following example shows how to write a higher order function in Python, which is an object-oriented programming language −

def twice(function): 
   return lambda x: function(function(x))  
def f(x): 
   return x + 3 
g = twice(f)
print g(7)      

It will produce the following output −

13
Advertisements