Last active
August 29, 2015 14:03
-
-
Save mathiasverraes/50b8a650015a545e9a29 to your computer and use it in GitHub Desktop.
More functional experiments
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 | |
define('map', 'map'); | |
function map($collection, $fn) { return array_map($fn, $collection); } | |
define('fold', 'fold'); | |
function fold($collection, $fn, $initial) { return array_reduce($collection, $fn, $initial); } | |
define('filter', 'filter'); | |
function filter($collection, $fn) { return array_filter($collection, $fn);} | |
function compose(array $collection, $fn, $args) | |
{ | |
$result = call_user_func_array($fn, array_merge([$collection], $args)); | |
$gotMore = func_num_args() > 3; | |
if($gotMore) { | |
$allArgs = func_get_args(); | |
array_shift($allArgs); | |
array_shift($allArgs); | |
array_shift($allArgs); | |
$nextFn = array_shift($allArgs); | |
$nextArgs = array_shift($allArgs); | |
$rest = $allArgs; | |
return call_user_func_array('compose', array_merge([$result, $nextFn, $nextArgs], $rest) ); | |
} | |
return $result; | |
} |
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 | |
compose( | |
[1, 2, 3], | |
map, [operator('*', 2)], | |
filter, [operator('>', 3)], | |
fold, [operator('+'), 0] | |
); | |
// returns 10 |
Yeah, literally had the idea in the shower this morning. Atom like :)
maybe function atom($name) { define($name, $name); }
sweet
What does operator()
do? Is it meant as a curried function (Haskell)?
It seems to work like this: (quick & dirty demo implementation)
<?php
function operator($operator, $defaultRightValue = null) {
return function($leftValue, $rightValue = null) use ($operator, $defaultRightValue) {
$rightValue = ($rightValue !== null) ? $rightValue : $defaultRightValue;
switch ($operator) {
case '+':
return $leftValue + $rightValue;
break;
case '*':
return $leftValue * $rightValue;
break;
case '>':
return $leftValue > $rightValue;
break;
default:
throw new InvalidArgumentException('Unknown operator');
}
};
}
seems like i'm mixing up two responsiblities (the operator part and the currying part) 👎
@turanct Using https://github.com/nikic/iter/blob/master/src/iter.fn.php#L68
But I agree that separating it into a simple (operator, l, r) ==> l operator r
and moving the currying out would be better
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very nice
define('map', 'map');