PHP code example of functional-php / pattern-matching

1. Go to this page and download the library: Download functional-php/pattern-matching library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

functional-php / pattern-matching example snippets



use FunctionalPHP\PatternMatching as m;

$fact = m\func([
    '0' => 1,
    'n' => function($n) use(&$fact) {
        return $n * $fact($n - 1);
    }
]);

$head = m\func([
    '(x:_)' => function($x) { return $x; },
    '_' => function() { throw new RuntimeException('empty list'); }
]);

$firstThree= m\func([
    '(x:y:z:_)' => function($x, $y, $z) { return [$x, $y, $z]; },
    '_' => function() { throw new RuntimeException('need at least 3 elements'); }
]);



use FunctionalPHP\PatternMatching as m;

function factorial($n) {
    return m\pmatch([
        '0' => 1,
        'n' => function($n) use(&$fact) {
            return $n * factorial($n - 1);
        }
    ], $n);
}

echo m\pmatch([
    '"toto"' => 'first',
    '[a, [b, c], d]' => 'second',
    '[a, _, (x:xs), c]' => 'third',
    '_' => 'default',
], [1, 2, ['a', 'b'], true]);
// third



use FunctionalPHP\PatternMatching as m;

print_r(m\extract([1, 2, ['a', 'b'], true], '[a, _, (x:xs), c]'));
// Array (
//     [a] => 1
//     [x] => a
//     [xs] => Array ( [0] => b )
//     [c] => 1
// )