Functional Programming
Mon Mar 27 2017
By: Chip Salim
Adopted from: Charles Scalfani
Pure Function
Functions that only operate on their input parameters.
Categories:
- Impure Functions
- Pure Functions:
- Not Useful Pure Functions
- Useful Pure Functions
Impure Pure Function
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);
Pure Function
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
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
Pure Function vs. Impure Function
Impure Function may change a variable somewhere deep in the code base.
Makes debugging harder.
Text
Immutability
Immutability in FP:
- There are no variables
- Recursive instead of Loop
// 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
Imperative vs. Declarative Language
Pure function doesn't eliminate "side effects" but rather confine them.
Refactoring
Functional Programming
By ilusi
Functional Programming
- 130