-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunction_composition.php
More file actions
41 lines (35 loc) · 897 Bytes
/
function_composition.php
File metadata and controls
41 lines (35 loc) · 897 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?php
declare(strict_types=1);
// Function composition
class Pipeline
{
private array $functions;
public function __construct(...$functions)
{
$this->functions = $functions;
}
public function process(/*$input*/)
{
return array_reduce(
// array_reverse($this->functions),
// fn($acc, $func) => $func($acc),
// $input
$this->functions,
fn($acc, $func) => fn($x) => $func($acc($x)),
fn($x) => $x
);
}
}
$double = fn($x) => $x * 2;
$increment = fn($x) => $x + 1;
$square = fn($x) => $x * $x;
$pipeline = new Pipeline($double, $increment, $square);
// echo $pipeline->process(5);
echo $pipeline->process()(5);
// $pipeline = fn($x) =>
// (fn($x) => $x*$x)(
// (fn($x) => $x+1)(
// (fn($x) => $x*2)($x)
// )
// );
// echo $pipeline(5);