An open API service indexing awesome lists of open source software.

https://github.com/atomicptr/phonad

Building blocks for functional programming in PHP, inspired by Haskell.
https://github.com/atomicptr/phonad

functional-programming php php-library

Last synced: 17 days ago
JSON representation

Building blocks for functional programming in PHP, inspired by Haskell.

Awesome Lists containing this project

README

          

# Phonad

Building blocks for functional programming in PHP, inspired by Haskell.

**Note**: This is an experiment to play around with Functional Programming in PHP

## Install

Install via composer:

```bash
$ composer require phonad/core
```

## Data Structures

### Maybe

Handles optional values without `null`.

```php
map(fn($n) => $n * 2)
->orElse(0); // 20
```

### Either

Error handling: `Right` for success, `Left` for failure.

```php
flatMap(fn($n) => $n > 5 ? Either::Right($n) : Either::Left("Too small"))
->either(fn($err) => "Error: $err", fn($val) => "Value: $val");
```

### ImmutableList

Immutable linked list (PDS).

```php
cons(0)
->filter(fn($n) => $n > 0); // [1, 2, 3]
```

## Effects

### Reader

Dependency injection via environment.

```php
map(fn($env) => "Env is: " . $env['mode']);
echo $logic->run(['mode' => 'production']);
```

### Writer

Pure logging alongside values.

```php
flatMap(fn($n) => Writer::of($n + 1, ["Incremented"]))
->run();
```

### IO

Lazy side effects.

```php
IO::make(function () use ($name) {
echo "Hello, $name!";
});

// Chain the logic (nothing actually happens yet)
$program = IO::of('world')
->map('strtoupper')
->flatMap(fn($name) => $sayHello($name));

// FIRE!
$program->run(); // Outputs: Hello, WORLD!
```

## License

MIT