Last active
December 13, 2021 08:30
-
-
Save timacdonald/7847ef40989ab80b41ce119558ec2074 to your computer and use it in GitHub Desktop.
Transducers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
namespace Transducers; | |
use Closure; | |
function compose(array $reducers): Closure | |
{ | |
$reducers = array_reverse($reducers); | |
return fn (Closure $step) => | |
fn ($accumulator, $current) => | |
array_reduce( | |
$reducers, | |
fn ($accumulator, $current) => $current($accumulator), | |
$step | |
)($accumulator, $current); | |
} | |
function filter(Closure $predicate): Closure | |
{ | |
return fn (Closure $step) => | |
fn ($accumulator, $current) => | |
$predicate($current) | |
? $step($accumulator, $current) | |
: $accumulator; | |
} | |
function map(Closure $callback): Closure | |
{ | |
return fn (Closure $step) => | |
fn ($accumulator, $current) => | |
$step($accumulator, $callback($current)); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
use function Transducers\compose; | |
use function Transducers\filter; | |
use function Transducers\map; | |
$double = fn ($value) => $value * 2; | |
$isEven = fn ($value) => ($value % 2) === 0; | |
$doubleEvens = compose([ | |
filter($isEven), | |
map($double), | |
]); | |
$xform = $doubleEvens(function ($accumulator, $current) { | |
$accumulator[] = $current; | |
return $accumulator; | |
}); | |
$result = array_reduce([2, 2, 3, 4], $xform, []); | |
// [4, 4, 8] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This was fun. Do not recommend.