public function testReduce() { $append = function ($xs, $x) { return array_merge($xs, [$x]); }; $this->assertEquals(Maybe::empty()->reduce($append, []), [], 'Nothing reduction.'); $this->assertEquals(Maybe::of(2)->reduce($append, []), [2], 'Just reduction.'); }
public function testMap() { $add2 = function ($x) { return $x + 2; }; $this->assertEquals(Maybe::empty()->map($add2)->fork(-1), -1, 'Nothing map.'); $this->assertEquals(Maybe::of(2)->map($add2)->fork(-1), 4, 'Just map.'); }
public function testChain() { $safeHalf = function ($x) { return $x % 2 == 0 ? Maybe::of($x / 2) : Maybe::empty(); }; $this->assertEquals($safeHalf(16)->chain($safeHalf)->fork(null), 4, 'Just chains.'); $this->assertEquals($safeHalf(5)->chain($safeHalf)->fork(null), null, 'Nothing chains.'); }
public function testConcat() { $maybes = [Maybe::empty(), Maybe::of(2), Maybe::empty()]; $acc = array_reduce($maybes, function ($acc, $x) { return $acc->concat($x); }, Maybe::empty()); $this->assertEquals(2, $acc->fork(5), 'Concatenates.'); }
public function testEquals() { $a = Maybe::empty(); $b = Maybe::of(new Value(2)); $c = Maybe::of(new Value(3)); $d = Maybe::of(new Value(3)); $this->assertEquals($a->equals($a), true, 'Two Nothing values.'); $this->assertEquals($a->equals($b), false, 'Just and Nothing.'); $this->assertEquals($b->equals($c), false, 'Unequal values.'); $this->assertEquals($c->equals($d), true, 'Equal values.'); }
public function testAp() { $add = function ($x) { return function ($y) use($x) { return $x + $y; }; }; $a = Maybe::of(2); $b = Maybe::of(4); $this->assertEquals(Maybe::of($add)->ap($a)->ap($b)->fork(null), 6, 'Applies to a Just.'); $this->assertEquals(Maybe::empty()->ap($a)->fork(-1), 2, 'Applies to a Nothing.'); }
public function testFork() { $this->assertEquals(Maybe::of(2)->fork(4), 2, 'Just fork.'); $this->assertEquals(Maybe::empty()->fork(4), 4, 'Nothing fork.'); }
public function testEmpty() { $this->assertInstanceOf('PhpFp\\Maybe\\Constructor\\Nothing', Maybe::empty(), 'The empty value is a nothing.'); }
public function testEmpty() { $this->assertInstanceOf('PhpFp\\Maybe\\Constructor\\Just', Maybe::of(2), 'The empty value is a nothing.'); $this->assertEquals(Maybe::of(2)->fork(-1), 2, 'Creates a Just value.'); }
/** * Functor map, derived from chain. * @param callable $f The mapping function. * @return Maybe The outer structure is preserved. */ public function map(callable $f) : Maybe { return $this->chain(function ($a) use($f) { return Maybe::of($f($a)); }); }