Skip to content

Instantly share code, notes, and snippets.

@Flushot
Last active August 19, 2016 23:23
Show Gist options
  • Save Flushot/5a377c6324342b63898bce0dc6ec100f to your computer and use it in GitHub Desktop.
Save Flushot/5a377c6324342b63898bce0dc6ec100f to your computer and use it in GitHub Desktop.
PHP functional programming sandbox
<?php
header('Content-Type: text/plain');
// y combinator
function y($F) {
$x = function ($f) use ($F) {
return $F(function () use ($f) {
return call_user_func_array($f($f), func_get_args());
});
};
return $x($x);
}
function compose() {
$funcs = func_get_args();
return function () use ($funcs) {
$result = func_get_args();
for ($i = count($funcs) - 1; $i >= 0; --$i) {
$result = call_user_func_array($funcs[$i], $result);
if ($i > 0) {
$result = [$result];
}
}
return $result;
};
}
// implementation //
$fibonacci = y(function ($fib) {
return function ($n) use ($fib) {
return $n > 1
? $fib($n - 1) + $fib($n - 2)
: $n;
};
});
echo "--- Fibonacci ---" . PHP_EOL;
for ($i = 0; $i < 20; ++$i) {
echo $fibonacci($i) . PHP_EOL;
}
function add($x) {
return function ($y) use ($x) {
return $x + $y;
};
}
function mul($x) {
return function ($y) use ($x) {
return $x * $y;
};
}
$add21 = add(21);
$mul3 = mul(3);
$add21mul3 = compose($add21, $mul3);
echo "--- Compose ---" . PHP_EOL;
echo $add21mul3(4) . PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment