PHPackages                             vjsingla/php-functional - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. vjsingla/php-functional

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

vjsingla/php-functional
=======================

Functors, Applicative and Monads are fascinating concept. Purpose of this library is to explore them in OOP PHP world.

1.0.0(1y ago)086MITPHPPHP ^7.1|^8.0|^8.1

Since Jul 10Pushed 1y agoCompare

[ Source](https://github.com/vjsingla/php-functional)[ Packagist](https://packagist.org/packages/vjsingla/php-functional)[ RSS](/packages/vjsingla-php-functional/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (4)Versions (4)Used By (0)

PHP Functional
==============

[](#php-functional)

[![Build Status](https://camo.githubusercontent.com/5e55b67f1d16eb265cb5a608786b94648d4751c85f2dc71d900da85a24aca3b6/68747470733a2f2f7472617669732d63692e6f72672f7769646d6f67726f642f7068702d66756e6374696f6e616c2e737667)](https://travis-ci.org/widmogrod/php-functional)[![Test Coverage](https://camo.githubusercontent.com/b0f97f90ae30d013281ce13e2e43ab2aeeb10decea4bdb39c0b152afcb07a78f/68747470733a2f2f6170692e636f6465636c696d6174652e636f6d2f76312f6261646765732f38393562646463393532616566636130643832612f746573745f636f766572616765)](https://codeclimate.com/github/widmogrod/php-functional/test_coverage)[![Maintainability](https://camo.githubusercontent.com/784fd154ad5be6a491bdb3d6a3163e0fa43182126a3a232c6727dd2354adb454/68747470733a2f2f6170692e636f6465636c696d6174652e636f6d2f76312f6261646765732f38393562646463393532616566636130643832612f6d61696e7461696e6162696c697479)](https://codeclimate.com/github/widmogrod/php-functional/maintainability)

Introduction
------------

[](#introduction)

Functional programing is a fascinating concept. The purpose of this library is to explore `Functors`, `Applicative Functors`and `Monads` in OOP PHP, and provide examples of real world use case.

Monad types available in the project:

- `State Monad`
- `IO Monad`
- `Free Monad`
- `Either Monad`
- `Maybe Monad`
- `Reader Monad`
- `Writer Monad`

Exploring functional programing space I noticed that working with primitive values from PHP is very hard and complicates implementation of many functional structures. To simplify this experience, set of higher order primitives is introduced in library:

- `Num`
- `Sum`
- `Product`
- `Stringg`
- `Listt` (a.k.a List Monad, since `list` is a protected keyword in PHP)

Applications
------------

[](#applications)

Known applications of this project

- [Algorithm W](https://github.com/widmogrod/php-algorithm-w) implemented in PHP based on Martin Grabmüller work.

Installation
------------

[](#installation)

```
composer require widmogrod/php-functional

```

Development
-----------

[](#development)

This repository follows [semantic versioning concept](http://semver.org/). If you want to contribute, just follow [CONTRIBUTING.md](/CONTRIBUTING.md)

Testing
-------

[](#testing)

Quality assurance is brought to you by:

- [PHPUnit](https://phpunit.de)
- [Eris](https://github.com/giorgiosironi/eris) - QuickCheck and property-based testing tools to the PHP and PHPUnit ecosystem.
- [PHP-CS-Fixer](https://github.com/FriendsOfPHP/PHP-CS-Fixer) - A tool to automatically fix PHP coding standards issues

```
composer test
composer fix

```

Use Cases
---------

[](#use-cases)

You can find more use cases and examples in the [example directory](/example/).

> **NOTE:** Don't be confused when browsing thought examples you will see phrase like "list functor" and in this library you will see ` Widmogrod\Primitive\Listt`. Monad is Functor and Applicative. You could say that Monad implements Functor and Applicative.

### List Functor

[](#list-functor)

```
use Widmogrod\Functional as f;
use Widmogrod\Primitive\Listt;

$list = f\fromIterable([
   ['id' => 1, 'name' => 'One'],
   ['id' => 2, 'name' => 'Two'],
   ['id' => 3, 'name' => 'Three'],
]);

$result = $list->map(function($a) {
    return $a['id'] + 1;
});

assert($result === f\fromIterable([2, 3, 4]));
```

### List Applicative Functor

[](#list-applicative-functor)

Apply function on list of values and as a result, receive list of all possible combinations of applying function from the left list to a value in the right one.

```
[(+3),(+4)]  [1, 2] == [4, 5, 5, 6]
```

```
use Widmogrod\Functional as f;
use Widmogrod\Primitive\Listt;

$listA = f\fromIterable([
    function($a) {
        return 3 + $a;
    },
    function($a) {
        return 4 + $a;
    },
]);
$listB = f\fromIterable([
    1, 2
]);

$result = $listA->ap($listB);

assert($result === f\fromIterable([4, 5, 5, 6]));
```

### Maybe Monoid

[](#maybe-monoid)

Using Maybe as an instance of Monoid simplifies concat and reduce operations by using Maybe's abstraction over potentially missing values. See an [example](example/MaybeMonoidTest.php) of constructing a person's full name from first, middle, and last without having to explicitly check if each part exists.

### Maybe and List Monad

[](#maybe-and-list-monad)

Extracting from a list of uneven values can be tricky and produce nasty code full of `if (isset)` statements. By combining List and Maybe Monad, this process becomes simpler and more readable.

```
use Widmogrod\Monad\Maybe;
use Widmogrod\Primitive\Listt;

$data = [
    ['id' => 1, 'meta' => ['images' => ['//first.jpg', '//second.jpg']]],
    ['id' => 2, 'meta' => ['images' => ['//third.jpg']]],
    ['id' => 3],
];

// $get :: String a -> Maybe [b] -> Maybe b
$get = function ($key) {
    return f\bind(function ($array) use ($key) {
        return isset($array[$key])
            ? Maybe\just($array[$key])
            : Maybe\nothing();
    });
};

$result = f\fromIterable($data)
    ->map(Maybe\maybeNull)
    ->bind($get('meta'))
    ->bind($get('images'))
    ->bind($get(0));

assert(f\valueOf($result) === ['//first.jpg', '//third.jpg', null]);
```

### Either Monad

[](#either-monad)

In `php` world, the most popular way of saying that something went wrong is to throw an exception. This results in nasty `try catch` blocks and many of if statements. Either Monad shows how we can fail gracefully without breaking the execution chain and making the code more readable. The following example demonstrates combining the contents of two files into one. If one of those files does not exist the operation fails gracefully.

```
use Widmogrod\Functional as f;
use Widmogrod\Monad\Either;

function read($file)
{
    return is_file($file)
        ? Either\Right::of(file_get_contents($file))
        : Either\Left::of(sprintf('File "%s" does not exists', $file));
}

$concat = f\liftM2(
    read(__DIR__ . '/e1.php'),
    read('aaa'),
    function ($first, $second) {
        return $first . $second;
    }
);

assert($concat instanceof Either\Left);
assert($concat->extract() === 'File "aaa" does not exists');
```

### IO Monad

[](#io-monad)

Example usage of `IO Monad`. Read input from `stdin`, and print it to `stdout`.

```
use Widmogrod\Monad\IO as IO;
use Widmogrod\Functional as f;

// $readFromInput :: Monad a -> IO ()
$readFromInput = f\mcompose(IO\putStrLn, IO\getLine, IO\putStrLn);
$readFromInput(Monad\Identity::of('Enter something and press '))->run();
```

### Writer Monad

[](#writer-monad)

The `Writer monad` is useful to keep logs in a pure way. Coupled with `filterM` for example, this allows you to know exactly why an element was filtered.

```
use Widmogrod\Monad\Writer as W;
use Widmogrod\Functional as f;
use Widmogrod\Primitive\Stringg as S;

$data = [1, 10, 15, 20, 25];

$filter = function($i) {
    if ($i % 2 == 1) {
        return W::of(false, S::of("Reject odd number $i.\n"));
    } else if($i > 15) {
      return W::of(false, S::of("Reject $i because it is bigger than 15\n"));
    }

    return W::of(true);
};

list($result, $log) = f\filterM($filter, $data)->runWriter();
```

### Reader Monad

[](#reader-monad)

The `Reader monad` provides a way to share a common environment, such as configuration information or class instances, across multiple functions.

```
use Widmogrod\Monad\Reader as R;
use Widmogrod\Functional as f;

function hello($name) {
    return "Hello $name!";
}

function ask($content)
{
    return R::of(function($name) use($content) {
        return $content.
               ($name == 'World' ? '' : ' How are you?');
    });
}

$r = R\reader('hello')
      ->bind('ask')
      ->map('strtoupper');

assert($r->runReader('World') === 'HELLO WORLD!')

assert($r->runReader('World') === 'HELLO GILLES! HOW ARE YOU?')
```

### Free Monad in PHP

[](#free-monad-in-php)

Imagine that you first write business logic and don't care about implementation details like:

- how and from where get user discounts
- how and where save products in basket
- and more ...

When your business logic is complete, then you can concentrate on those details.

Free monad enables you to do exactly that, and more:

- Write business logic first
- Write your own DLS (domain specific language)
- Decouple implementation from interpretation.

#### Echo program

[](#echo-program)

Example Free Monad example of `echo program` can be found here:

- See source code of [FreeMonadTest.php](/example/FreeMonadTest.php) - example based on second implementation of Free, based on [Haskell implementation](https://hackage.haskell.org/package/free-4.12.4/docs/Control-Monad-Free-Class.html)

#### DSL for `BDD` tests

[](#dsl-for-bdd-tests)

Example that use `Free Monad` to creates simple DSL (Domain Specific Language) to define BDD type of framework:

- See source code of [FreeBddStyleDSLTest.php](/example/FreeBddStyleDSLTest.php)

```
$state = [
    'productsCount' => 0,
    'products' => [],
];

$scenario =
    Given('Product in cart', $state)
        ->When("I add product 'coca-cola'")
        ->When("I add product 'milk'")
        ->Then("The number of products is '2'");

$result = $scenario->Run([
    "/^I add product '(.*)'/" => function ($state, $productName) {
        $state['productsCount'] += 1;
        $state['products'][] = $productName;

        return $state;
    },
], [
    "/^The number of products is '(\d+)'/" => function ($state, int $expected) {
        return $state['productsCount'] === $expected;
    },
]);
```

#### Free Monad Calculator example

[](#free-monad-calculator-example)

Example of a `DSL` for a naive calculator that is implemented by using FreeMonad.

Free monad can be interpreted as a real calculator or calculation formatter a.k.a. pretty printer. Additional thing that I wanted to tackle was a Free Monad Optimisation.

Considering that Free Monad is like AST, question arose in my mind - can I travers it and update it to simplify computation? Hot to do it? What are limitation of Free Monad? Calculator example is an outcome of those questions.

- See source code of [FreeCalculatorTest.php](/example/FreeCalculatorTest.php)

```
$calc = mul(
    sum(int(2), int(1)),
    sum(int(2), int(1))
);

$expected = '((2+1)^2)';

$result = foldFree(compose(interpretPrint, optimizeCalc), $calc, Identity::of);
$this->assertEquals(
    Identity::of(Stringg::of($expected)),
    $result
);
```

Haskell `do notation` in PHP
----------------------------

[](#haskell-do-notation-in-php)

Why Haskell's do notation is interesting?

In Haskell is just an "syntax sugar" and in many ways is not needed, but in PHP control flow of monads can be hard to track.

Consider example, that use only chaining `bind()`and compare it to the same version but with `do notation` in PHP.

### Control flow without do notation

[](#control-flow-without-do-notation)

```
$result = Identity::of(1)
    ->bind(function ($a) {
        return Identity::of(3)
            ->bind(function ($b) use ($a) {
                return Identity::of($a + $b)
                    ->bind(function ($c) {
                        return Identity::of($c * $c);
                    });
            });
    });

$this->assertEquals(Identity::of(16), $result);
```

### Control flow with do notation

[](#control-flow-with-do-notation)

```
$result = doo(
    let('a', Identity::of(1)),
    let('b', Identity::of(3)),
    let('c', in(['a', 'b'], function (int $a, int $b): Identity {
        return Identity::of($a + $b);
    })),
    in(['c'], function (int $c): Identity {
        return Identity::of($c * $c);
    })
);

assert($result === Identity::of(16));
```

Everyone needs to judge by itself, but in my opinion `do notation`improve readability of code in PHP.

#### Book `Functional PHP` by Gilles Crettenand [![](functional-php.png)](https://www.packtpub.com/application-development/functional-php)

[](#book-functional-php-by-gilles-crettenand-)

In recently published book [`Functional PHP` by Gilles Crettenand](https://www.packtpub.com/application-development/functional-php), you can learn more applications of `widmogrod/php-functional`, see how it compares to other projects and how in an effortless way apply functional thinking in daily work.

[Buy the book at PacktPub](https://www.packtpub.com/application-development/functional-php)

References
----------

[](#references)

Here links to their articles`/`libraries that help me understood the domain:

-
-
- [http://adit.io/posts/2013-04-17-functors,\_applicatives,\_and\_monads\_in\_pictures.html](http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html)
-
-
-
-
-
-

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance33

Infrequent updates — may be unmaintained

Popularity9

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 89.6% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

677d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/0c5cebdcac0122b12f25f7a23ddd21767c3ec4d94f5f78406c608588b18a7469?d=identicon)[vikramjeetsingla](/maintainers/vikramjeetsingla)

---

Top Contributors

[![widmogrod](https://avatars.githubusercontent.com/u/164249?v=4)](https://github.com/widmogrod "widmogrod (476 commits)")[![krtek4](https://avatars.githubusercontent.com/u/963772?v=4)](https://github.com/krtek4 "krtek4 (27 commits)")[![ilario-pierbattista](https://avatars.githubusercontent.com/u/987038?v=4)](https://github.com/ilario-pierbattista "ilario-pierbattista (12 commits)")[![vjsingla](https://avatars.githubusercontent.com/u/7846017?v=4)](https://github.com/vjsingla "vjsingla (5 commits)")[![tPl0ch](https://avatars.githubusercontent.com/u/115348?v=4)](https://github.com/tPl0ch "tPl0ch (4 commits)")[![nick-zh](https://avatars.githubusercontent.com/u/3214182?v=4)](https://github.com/nick-zh "nick-zh (2 commits)")[![eduardogr](https://avatars.githubusercontent.com/u/8736983?v=4)](https://github.com/eduardogr "eduardogr (2 commits)")[![safareli](https://avatars.githubusercontent.com/u/1932383?v=4)](https://github.com/safareli "safareli (1 commits)")[![nekufa](https://avatars.githubusercontent.com/u/405067?v=4)](https://github.com/nekufa "nekufa (1 commits)")[![mattjmattj](https://avatars.githubusercontent.com/u/1842012?v=4)](https://github.com/mattjmattj "mattjmattj (1 commits)")

###  Code Quality

TestsPHPUnit

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/vjsingla-php-functional/health.svg)

```
[![Health](https://phpackages.com/badges/vjsingla-php-functional/health.svg)](https://phpackages.com/packages/vjsingla-php-functional)
```

###  Alternatives

[widmogrod/php-functional

Functors, Applicative and Monads are fascinating concept. Purpose of this library is to explore them in OOP PHP world.

3726.6M10](/packages/widmogrod-php-functional)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
