Skip to content

Instantly share code, notes, and snippets.

@mathiasverraes
Last active August 29, 2015 14:03
Show Gist options
  • Save mathiasverraes/50b8a650015a545e9a29 to your computer and use it in GitHub Desktop.
Save mathiasverraes/50b8a650015a545e9a29 to your computer and use it in GitHub Desktop.
More functional experiments
<?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;
}
<?php
compose(
[1, 2, 3],
map, [operator('*', 2)],
filter, [operator('>', 3)],
fold, [operator('+'), 0]
);
// returns 10
@turanct
Copy link

turanct commented Jul 7, 2014

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) 👎

@mathiasverraes
Copy link
Author

@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