PHP code example of bartfeenstra / fu

1. Go to this page and download the library: Download bartfeenstra/fu 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/ */

    

bartfeenstra / fu example snippets



use BartFeenstra\Functional as F;
use BartFeenstra\Functional\Iterable as I;
use BartFeenstra\Functional\Predicate as P;
use function BartFeenstra\Functional\Iterable\iter;


// Arrays.
$iterator = iter([3, 1, 4]);

// \Traversable (that (return callables that...) return iterators.
$callable = function (){
  return function () {
    return iter([]);
  };
};
$iterator = iter($callable);

// Existing universal iterators are passed through.
$iterator = iter([]);
assert($iterator === iter($iterator));

// Objects can expose universal iterators as well.
$toIterator = new class() implements I\ToIterator {
  public function iter(): I\Iterator {
    return iter([]);
  }
};
$iterator = iter($toIterator);


$carrier = [];
$list = [3, 1, 4];
iter($list)->each(function (int $i) use (&$carrier) {
  $carrier[] = $i;
});
assert($list === $carrier);


$result = iter([3, 1, 4])->filter(P\gt(2));
assert([0 => 3, 2 => 4] === $result->toArray());


$found = iter([3, 1, 4, 1, 5, 9])->find(P\gt(4));
assert(new I\SomeItem(5, 4) == $found);


$original = [3, 1, 4];
$expected = [9, 3, 12];
$result = iter($original)->map(function (int $i): int {
  return 3 * $i;
});
assert($expected === $result->toArray());


$original = [
    3 => 'c',
    1 => 'a',
    4 => 'd',
];
$expected = [
    9 => 'c',
    3 => 'a',
    12 => 'd',
];
$result = iter($original)->mapKeys(function (string $value, int $key): int {
  return 3 * $key;
});
assert($expected === $result->toArray());


$list = [3, 1, 4];
$sum = iter($list)->reduce(function (int $sum, int $item): int {
  return $sum + $item;
});
assert(new F\SomeValue(8) == $sum);


$start = 2;
$list = [3, 1, 4];
$total = iter($list)->fold(function (int $total, int $item): int {
  return $total + $item;
}, $start);
assert(10 === $total);


$start = 2;
$list = [3, 1, 4, 1, 5, 9];
$result = iter($list)->take(4);
assert([3, 1, 4, 1] === $result->toArray());


$start = 2;
$list = [3, 1, 4, 1, 5, 9];
$result = iter($list)->takeWhile(P\le(3));
assert([3, 1] === $result->toArray());


$start = 2;
$list = [3, 1, 4, 1, 5, 9];
$result = iter($list)->slice(2, 3);
assert([2 => 4, 3 => 1, 4 => 5] === $result->toArray());


$list = [3, 1, 4, 1, 5, 9];
$min = iter($list)->min();
assert(new F\SomeValue(1) == $min);


$list = [3, 1, 4, 1, 5, 9];
$max = iter($list)->max();
assert(new F\SomeValue(9) == $max);


$list = [3, 1, 4, 1, 5, 9];
$sum = iter($list)->sum();
assert(new F\SomeValue(23) == $sum);


$list = [3, 1, 4];
$iterator = iter($list)->forever();
$expected = [3, 1, 4, 3, 1, 4, 3];
assert($expected === iterator_to_array($iterator->take(7), false));


$one = [3, 1, 4];
$two = [1, 5, 9];
$three = [2, 9, 2];
$zip = iter($one)->zip($two, $three);
$expected = [[3, 1, 2], [1, 5, 9], [4, 9, 2]];
assert($expected === iterator_to_array($zip));


$array = [
    'a' => 'A',
    'b' => 'B',
    'c' => 'C',
];
$indexed = iter($array)->list();
$expected = ['A', 'B', 'C'];
assert($expected === iterator_to_array($indexed));


$array = [
    'a' => 'A',
    'b' => 'B',
    'c' => 'C',
];
$keys = iter($array)->listKeys();
$expected = ['a', 'b', 'c'];
assert($expected === iterator_to_array($keys));


$array = [
    'a' => 3,
    'b' => 1,
    'c' => 4,
];
$flipped = iter($array)->flip();
$expected = [
    3 => 'a',
    1 => 'b',
    4 => 'c',
];
assert($expected === $flipped->toArray());


$array = [3, 1, 4];
$reverse = iter($array)->reverse();
assert([4, 1, 3] === $reverse->toArray());


$array = [3, 1, 4, 1, 5, 9];
assert(new I\SomeItem(3, 0) == iter($array)->first());


$array = [3, 1, 4, 1, 5, 9];
assert(new I\SomeItem(9, 5) == iter($array)->last());


assert(TRUE === iter([])->empty());
assert(FALSE === iter([3, 1, 4])->empty());



$array = [
    3 => 'c',
    1 => 'a',
    4 => 'd',
];
// ::sort() also takes an optional custom comparison callable.
$sort = iter($array)->sort();
$expected = [
    1 => 'a',
    3 => 'c',
    4 => 'd',
];
assert($expected === iterator_to_array($sort));


$array = [
    'c' => 3,
    'a' => 1,
    'd' => 4,
];
// ::sortKeys() also takes an optional custom comparison callable.
$sort = iter($array)->sortKeys();
$expected = [
    'a' => 1,
    'c' => 3,
    'd' => 4,
];
assert($expected === iterator_to_array($sort));


$arrayOne = [3, 1, 4];
$arrayTwo = [1, 5, 9];
$arrayThree = [2, 6, 5];
$iterator = iter($arrayOne)->chain($arrayTwo, $arrayThree);
$expected = [3, 1, 4, 1, 5, 9, 2, 6, 5];
assert($expected === $iterator->toArray());


$array = [
    [3, 1, 4],
    [1, 5, 9],
    [2, 6, 5],
];
$iterator = iter($array)->flatten();
$expected = [3, 1, 4, 1, 5, 9, 2, 6, 5];
assert($expected === $iterator->toArray());


$objectOne = new \stdClass();
$objectTwo = new \stdClass();
$array = [0, false, false, null, [], [], '0', $objectOne, $objectOne, $objectTwo];
$iterator = iter($array)->unique();
$expected = [
    0 => 0,
    1 => false,
    3 => null,
    4 => [],
    6 => '0',
    7 => $objectOne,
    9 => $objectTwo,
];
assert($expected === $iterator->toArray());


// Try executing a callable, catch all exceptions, and output a Result.
$result = F\try_except(function () {/** ... */});

// Try executing a callable, catch all Foo, Bar, Baz, and Qux exceptions, and output a Result.
$result = F\try_except(function () {/** ... */}, Foo::class, Bar::class, Baz::class, Qux::class);

// Try executing a callable at most twice, catch all exceptions, and output a Result.
$result = F\retry_except(function () {/** ... */});

// Try executing a callable at most 5 times, catch all Foo, Bar, Baz, and Qux exceptions, and output a Result.
$result = F\retry_except(function () {/** ... */}, 5, Foo::class, Bar::class, Baz::class, Qux::class);


// All values strictly identical to TRUE.
$predicate = P\true();

// All values strictly identical to FALSE.
$predicate = P\false();

// All values that evaluate to TRUE.
$predicate = P\truthy();

// All values that evaluate to FALSE.
$predicate = P\falsy();

// All values strictly identical to 0.
$predicate = P\id(0);

// All values equal to "Apples and oranges".
$predicate = P\eq('Apples and oranges');

// All values greater than 9.
$predicate = P\gt(9);

// All values greater than or equal to 99.
$predicate = P\ge(99);

// All values lesser than 15.
$predicate = P\lt(15);

// All values lesser than or equal to 666.
$predicate = P\le(666);

// All values that are instances of Foo, Bar, Baz, or Qux.
$predicate = P\instance_of(Foo::class, Bar::class, Baz::class, Qux::class);

// One or more values are lesser than 0 OR greater than 9.
$predicate = P\any(P\lt(0), P\gt(9));

// All values are greater than 0 AND lesser than 9.
$predicate = P\all(P\gt(0), P\lt(9));

// All values different from "Apples and oranges".
$predicate = P\not(P\eq('Apples and oranges'));


use BartFeenstra\Functional\Option;
use BartFeenstra\Functional\Some;
use BartFeenstra\Functional\SomeValue;
use BartFeenstra\Functional\None;
function get_option(): Option {
    if (true) {
        return new SomeValue(666);
    }
    return new None();
}
function handle_option(Option $value) {
    if ($value instanceof Some) {
        print sprintf('The value is %s.', $value());
    }
    // $value is an instance of None.
    else {
        print 'No value could be retrieved.';
    }
}
handle_option(get_option());


use BartFeenstra\Functional\Ok;
use BartFeenstra\Functional\OkValue;
use BartFeenstra\Functional\Result;
use BartFeenstra\Functional\ThrowableError;
function get_result(): Result {
    try {
        // Do some things that may throw a ResultComputationException.
        return new OkValue(666);
    }
    catch (\ResultComputationException $e) {
        return new ThrowableError($e);
    }
}
function handle_result(Result $result) {
    if ($result instanceof Ok) {
        print sprintf('The value is %s.', $result());
    }
    // $value is an instance of Error.
    else {
        print sprintf('An error occurred: %s.', $result);
    }
}
handle_result(get_result());


$originalFunction = function (string $a, string $b, string $c, string $d): string {
    return $a . $b . $c . $d;
};

// Fix the two first/left-handed arguments.
$newFunction = F\apply_l($originalFunction, 'A', 'B');
assert('ABCD' === $newFunction('C', 'D'));

// Fix the two last/right-handed arguments.
$newFunction = F\apply_r($originalFunction, 'C', 'D');
assert('ABCD' === $newFunction('A', 'B'));

// Fix two arguments by index/in the middle.
$newFunction = F\apply_i($originalFunction, 1, 'B', 'C');
assert('ABCD' === $newFunction('A', 'D'));


$originalFunction = function (string $a, string $b, string $c, string $d = 'D'): string {
    return $a . $b . $c . $d;
};

assert('ABCD' === F\curry($originalFunction)('A')('B')('C'));