php-core

Last updated: 2015-10-09 05:33:28 +0100

Upstream URL: git clone http://chriswarbo.net/git/php-core.git

Repo

View repository

View issue tracker

Contents of README follows


= PHP Core Extensions =

This is a “polyfill” which provides some core language functionality not offered by PHP ‘out of the box’. Includes:

== Callable Operators ==

In regular PHP, we can’t treat operators as functions, eg.

<pre><code>$total = array_reduce($penalties, function($x, $y) { return $x - $y; }, $score); if ($errors) { throw current($errors); }</code></pre>

PHP Core provides an ‘op’ function to work around this:

<pre><code>$total = array_reduce($penalties, op('-'), $score); array_map(op('throw'), $errors);</code></pre>

Core’s higher-order functions apply ‘op’ automatically.

== Partial Application ==

By default, PHP’s functions are all-or-nothing: you can either call them now, with whatever values you have, or you must wait until later:

<pre><code>$r1 = func($a, $b, $c, null, null, null); $r2 = function($d, $e, $f) use ($a, $b, $c) { return func($a, $b, $c, $d, $e, $f); };</code></pre>

Partial application lets you pass in some arguments now and the rest later:

<pre><code>$r3 = papply('func', $a, $b, $c);</code></pre>

== Currying ==

Curried functions don’t need partial application: they collect up the right number of arguments automatically:

<pre><code>$f = curry(function($w, $x, $y, $z) { return func_get_args(); }); $g = $f(10); $h = $g(20); $i = $h(30, 40); // $i === [10, 20, 30, 40]</code></pre>

They also pass surplus arguments to their return value:

<pre><code>$action = curry(function($action) { return "ldap_{$action}"; }); $action('bind', $connection, $dn, $password);</code></pre>

Some of Core’s higher-order functions will automatically curry their arguments and results.

== Named Closures ==

PHP separates functions into those which are named (AKA ‘global functions’) and those which are anonymous (AKA ‘Closure instances’):

<pre><code>function i_am_named($x) { return $x; } $i_am_anonymous = function($x) { return $x; };</code></pre>

PHP allows named functions to be treated like anonymous functions:

<pre><code>$i_act_anonymously = 'i_am_named';</code></pre>

Core allows anonymous functions to be named:

<pre><code>defun('i_act_named', $i_am_anonymous);</code></pre>

== Extras ==

A few handy functions are provided too:

<ul> <li>compose: Function composition</li> <li>call: Like call_user_func but uses op and curry</li> <li>uncurry: Like call_user_func_array but uses op and curry</li> <li>up_to: Like range but handles 0 correctly</li> <li>arity: Counts a function’s arguments (handles defun, papply, op and curry)</li> </ul>