Mon Mar 27 2017
By: Chip Salim
Adopted from: Charles Scalfani
Functions that only operate on their input parameters.
Categories:
Functions that read and/or write to an out-of-scope variable.
// Example #1
$var = 10;
function add($a, $b) {
$var = $a + $b;
return $var;
}
print $var; // Print 10
print add(1, 2); // Print 13
// Examples #2
send($request);
update($query);
write($fileName);
Functions that only operate on their input parameters.
// Example #1
function addTen() {
return 10;
}
print addTen(); // Print 10
// Better use a constant
define("TEN", 10);
print TEN; // Print 10
Not-Useful Pure Function
Functions that only operate on their input parameters and return a value.
// Example #1
function add($a, $b) {
return $a + $b;
}
print add(1, 2); // Print 3
Useful Pure Function
Impure Function may change a variable somewhere deep in the code base.
Makes debugging harder.
Text
Immutability in FP:
// Example #1 - Using loop
function add() {
$var = 10;
for ($i = 0; $i <= 10; $i++) {
$var += $i;
}
return $var;
}
print add(); // Print 65
// Example #2 - using recursion
function add($start, $end, $var) {
if ($start > $end) {
return $var;
}
return add($start + 1, $end, $var + $start);
}
print add(); // Print 65
Pure function doesn't eliminate "side effects" but rather confine them.