• Stars
    star
    296
  • Rank 140,464 (Top 3 %)
  • Language
    PHP
  • Created over 11 years ago
  • Updated about 9 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A simple Monad library for PHP

MonadPHP

This is a basic Monad library for PHP.

Usage

Values are "wrapped" in the monad via either the constructor: new MonadPHP\Identity($value) or the unit() method on an existing instance: $monad->unit($value);

Functions can be called on the wrapped value using bind():

use MonadPHP\Identity;
$monad = new Identity(1);
$monad->bind(function($value) { var_dump($value); });
// Prints int(1)

All calls to bind return a new monad instance wrapping the return value of the function.

 use MonadPHP\Identity;
$monad = new Identity(1);
$monad->bind(function($value) {
        return 2 * $value;
    })->bind(function($value) { 
        var_dump($value); 
    });
// Prints int(2)

Additionally, "extracting" the raw value is supported as well (since this is PHP and not a pure functional language)...

use MonadPHP\Identity;
$monad = new Identity(1);
var_dump($monad->extract());
// Prints int(1)

Maybe Monad

One of the first useful monads, is the Maybe monad. The value here is that it will only call the callback provided to bind() if the value it wraps is not null.

use MonadPHP\Maybe;
$monad = new Maybe(1);
$monad->bind(function($value) { var_dump($value); });
// prints int(1)

$monad = new Maybe(null);
$monad->bind(function($value) { var_dump($value); });
// prints nothing (callback never called)...

The included Chain monad does the same thing, but providing a short-cut implementation for objects:

use MonadPHP\Chain;
$monad = new Chain($someChainableObject);
$obj = $monad->call1()->call2()->nonExistantMethod()->call4()->extract();
var_dump($obj);
// null

This can prevent errors when used with chaining...

List Monad

This abstracts away the concept of a list of items (an array):

use MonadPHP\ListMonad;
$monad = new ListMonad(array(1, 2, 3, 4));
$doubled = $monad->bind(function($value) { return 2 * $value; });
var_dump($doubled->extract());
// Prints array(2, 4, 6, 8)

Note that the passed in function gets called once per value, so it only ever deals with a single element, never the entire array...

It also works with any Traversable object (like iterators, etc). Just be aware that returning the new monad that's wrapped will alwyas become an array...

Composition

These Monads can be composed together to do some really useful things:

use MonadPHP\ListMonad;
use MonadPHP\Maybe;

$monad = new ListMonad(array(1, 2, 3, null, 4));
$newMonad = $monad->bind(function($value) { return new Maybe($value); });
$doubled = $newMonad->bind(function($value) { return 2 * $value; });
var_dump($doubled->extract());
// Prints array(2, 4, 6, null, 8)

Or, what if you want to deal with multi-dimensional arrays?

use MonadPHP\ListMonad;
$monad = new ListMonad(array(array(1, 2), array(3, 4), array(5, 6)));
$newMonad = $monad->bind(function($value) { return new ListMonad($value); });
$doubled = $newMonad->bind(function($value) { return 2 * $value; });
var_dump($doubled->extract());
// Prints array(array(2, 4), array(6, 8), array(10, 12))

There also exist helper constants on each of the monads to get a callback to the unit method:

$newMonad = $monad->bind(Maybe::unit);
// Does the same thing as above 

Real World Example

Imagine that you want to traverse a multi-dimensional array to create a list of values of a particular sub-key. For example:

$posts = array(
    array("title" => "foo", "author" => array("name" => "Bob", "email" => "[email protected]")),
    array("title" => "bar", "author" => array("name" => "Tom", "email" => "[email protected]")),
    array("title" => "baz"),
    array("title" => "biz", "author" => array("name" => "Mark", "email" => "[email protected]")),
);

What if we wanted to extract all author names from this data set. In traditional procedural programming, you'd likely have a number of loops and conditionals. With monads, it becomes quite simple.

First, we define a function to return a particular index of an array:

function index($key) {
    return function($array) use ($key) {
        return isset($array[$key]) ? $array[$key] : null;
    };
}

Basically, this just creates a callback which will return a particular array key if it exists. With this, we have everything we need to get the list of authors.

$postMonad = new MonadPHP\ListMonad($posts);
$names = $postMonad
    ->bind(MonadPHP\Maybe::unit)
    ->bind(index("author"))
    ->bind(index("name"))
    ->extract();

Follow through and see what happens!

More Repositories

1

password_compat

Compatibility with the password_* functions that ship with PHP 5.5
PHP
2,151
star
2

RandomLib

A library for generating random numbers and strings
PHP
840
star
3

PHPPHP

A PHP VM implementation in PHP
PHP
811
star
4

php-compiler

A compiler. For PHP
PHP
793
star
5

PhpGenerics

Here be dragons
PHP
530
star
6

filterus

A simple filtering library for PHP
PHP
454
star
7

PHP-PasswordLib

A library for generating and validating passwords
PHP
373
star
8

php-cfg

A Control Flow Graph implementation in PHP
PHP
243
star
9

Tuli

A static analysis engine
PHP
168
star
10

phpvm

A PHP version manager for CLI PHP
PHP
150
star
11

PHP-Yacc

A PHP port of kmyacc
PHP
149
star
12

PHP-CryptLib

A Cryptography Library for PHP
PHP
144
star
13

FFIMe

A FFI Wrapper library and header parser!
PHP
136
star
14

SecurityLib

SecurityLib
PHP
126
star
15

Stauros

A fast XSS sanitization library for PHP
PHP
118
star
16

php-security-scanner

A static security scanner for PHP
PHP
97
star
17

Tari-PHP

A middleware proposal for PHP
PHP
78
star
18

password-policy

A password policy enforcer for PHP and JavaScript
PHP
77
star
19

php-ast-visualizer

An AST visualizer, for PHP
PHP
75
star
20

prerano

A new language for PHP
PHP
65
star
21

php-preprocessor

A PreProcessing library for PHP
PHP
49
star
22

ErrorExceptions

A library for converting core PHP errors into ErrorExceptions
PHP
43
star
23

PHP-BrainFuck

A brainfuck interpreter for PHP
PHP
42
star
24

php-c-parser

A C parser built in and for PHP (yes, it's a bad idea)...
PHP
40
star
25

random_compat

Compatibility library for proposed simplified random number generator
PHP
40
star
26

php-llvm

A "lightweight" wrapper around LLVM-C in native PHP
PHP
39
star
27

php-types

A PHP Type reconstruction library
PHP
36
star
28

php-compiler-toolkit

A compiler toolkit. For PHP (yes, I am creative at naming things)...
PHP
30
star
29

resume

Anthony Ferrara's Resume (CV)
30
star
30

php-math-parser

A Shunting-Yard Based Math Engine For PHP
PHP
29
star
31

Protocol-Lib

A library for runtime checking of protocols
PHP
27
star
32

php-optimizer

A CFG Optimizer for PHP
PHP
24
star
33

RequirePHP

A RequireJS clone in PHP - As a dependency Loader
PHP
22
star
34

ballandchain

A PHP implementation of BallAndChain
PHP
20
star
35

libgccffi

libgccffi interface for PHP, based on 7.4's FFI and FFIMe
PHP
19
star
36

MixinPHP

A test mixin library for super-happy-crazy-time
PHP
18
star
37

php-ndata

NData PECL extension for dealing with native data types
C
15
star
38

cpu_assembler

An assembler for my custom CPU
PHP
13
star
39

TrueObjectStore

What SPLObjectStorage Should Have Been
PHP
13
star
40

haas

Hugs, As A Service
HTML
13
star
41

programming-with-anthony

Scripts for the Programming With Anthony series on YouTube
11
star
42

php-object-symbolresolver

A linux object file (ELF) parser
PHP
10
star
43

password-bad-web-app

A bad web app, to demonstrate password hashing issues DO NOT USE!!!
PHP
10
star
44

quality-checker

PHP Quality Checker
PHP
10
star
45

blog.ircmaxell.com

blog.ircmaxell.com future site
Less
9
star
46

Primitives

A collection of primitive types for PHP
PHP
6
star
47

blog-ideas

6
star
48

cryptography-presentation-tnphp

Slides for the Cryptography Presentation done at TrueNorthPHP on Nov 2, 2012
JavaScript
6
star
49

Ircmaxell.com

PHP
5
star
50

ZPP

A PHP implementation of Zend-Parse-Parameters
PHP
5
star
51

XssBadWebApp

A Intentionally Vulnerable Bad Web Application With XSS Vulnerabilities - *DO NOT USE!!!*
PHP
5
star
52

CodeReviewSecurityRepo

Code Review for Security Repository Of Code To Review
PHP
5
star
53

password-advice

The website behind password-advice.com
4
star
54

SetLib

A Badly Named Playground
PHP
4
star
55

DontBeStupid-Presentation

A repo of the Don't Be Stupid, Grasp Solid presentation at NYPHP on 5-22-12
JavaScript
3
star
56

hashguesser

Hash guesser
JavaScript
3
star
57

jQuery.OOP

A pseudo-port of MooTools OOP to jQuery
2
star
58

Intervalometer

An intervalometer
Arduino
2
star
59

BehaviorTest

A Proof-Of-Concept behavioral testing app
PHP
2
star
60

password-hashing-mini-presentation

Password-Hashing-Mini-Presentation
JavaScript
2
star
61

PHPTest

A Unit Testing Framework for PHP
PHP
2
star
62

ITL

Some silly test programming language thingy
Ruby
1
star
63

solid-presentation-tnphp

Slides for the SOLID OO Design presentation at True North PHP on Nov 3, 2012
JavaScript
1
star
64

PreProcessor

A trivial attempt at a PHP preprocessor (DO NOT USE!!! Experimental ONLY!!!)
PHP
1
star
65

jsGoodies

Just some JS snipits I've found useful
JavaScript
1
star
66

8bit-cpu-v2

Ruby
1
star