Skip to content

Instantly share code, notes, and snippets.

@tpunt

tpunt/file.md Secret

Last active Feb 15, 2017
Embed
What would you like to do?
Examples for the short closure syntax RFC

The Knapsack project is a good example of why shorthand closures would be helpful. It's documentation examples are bloated by the current closure syntax.

Example 1

Normal closures:

$result = reduce(
    map(
        [1, 2], 
        function($v) {return $v * 2;}
    ),
    function($tmp, $v) {return $tmp + $v;},
    0
);

echo $result; // 6

Arrow functions:

$result = reduce(
    map([1, 2], fn($v) => $v * 2),
    fn($tmp, $v) => $tmp + $v,
    0
);

echo $result; // 6

Example 2

Normal closures:

$result = Collection::from([1, 2])
    ->map(function($v) {return $v * 2;})
    ->reduce(function($tmp, $v) {return $tmp + $v;}, 0);

echo $result; // 6

Arrow functions:

$result = Collection::from([1, 2])
    ->map(fn($v) => $v * 2)
    ->reduce(fn($tmp, $v) => $tmp + $v, 0);

echo $result; // 6

Examples from the project's source code

https://github.com/DusanKasan/Knapsack/blob/24078b72beff714b7d71db78663e3e429ec4e788/src/collection_functions.php#L426

// normal closures
function groupByKey($collection, $key)
{
    $generatorFactory = function () use ($collection, $key) {
        return groupBy(
            filter(
                $collection,
                function ($item) use ($key) {
                    return isCollection($item) && has($item, $key);
                }
            ),
            function($value) use ($key) {
                return get($value, $key);
            }
        );
    };

    return new Collection($generatorFactory);
}
// arrow functions
function groupByKey($collection, $key)
{
    $generatorFactory = fn() =>
        groupBy(
            filter(
                $collection,
                fn($item) => isCollection($item) && has($item, $key)
            ),
            fn($value) => get($value, $key);
        );

    return new Collection($generatorFactory);
}

https://github.com/DusanKasan/Knapsack/blob/24078b72beff714b7d71db78663e3e429ec4e788/src/collection_functions.php#L683

// normal closures
function reject($collection, callable $function)
{
    return filter(
        $collection,
        function($value, $key) use ($function) {
            return !$function($value, $key);
        }
    );
}
// arrow functions
function reject($collection, callable $function)
{
    return filter($collection, fn($value, $key) => !$function($value, $key));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.