Functional Programming in PHP Book

Page 24

tail_sum()

tail_sum() should have $running_total set to 1 by default instead of 0.

Page 86

$x has incorrect return type

$x should return a type of Only and not an integer as defined in the book. So $x should be:

$x = function($value) {
   return Only::pack($value + 2);
};

Therefore the return types of $a and $b (declared in the same code block as the definition of $x in the book) now need to be updated to match as well.

$a = Only::pack(2)->map($x); // Only(4)
$b = $x(2); // Only(4)

Note the changes to the comments so that it now indicates a return value of Only(4).

$y definition missing

The definition of $y was missing from the book and should be:

$y = function($value) {
   return Only::pack($value * 5);
};

With this in place the third law is now provable.

Page 88

Maybe monad shouldn't overload map()

Firstly, map() should be defined as:

public function map($function) {
    return $function($this->container);
}

Then we need to add another method to the class to allow for the additional functionality.

public function mapAndPack($function) {
    return $this->isNothing() ?
        $this :
        static::pack($this->map($function));
}

Finally this means that the call applying $verify_names must also be amended on the base of page 88.

$sth = $pdo->prepare("SELECT * FROM umuntu");
$sth->execute();
$row = $sth->fetch(PDO::FETCH_LAZY);
$verify_names = function($value) {
    return $value->ibizo . ' (verified)';
};
echo 'Name: ' . Maybe::pack($row)->
    mapAndPack($verify_names)->
    getOrElse('Unknown');