1. Go to this page and download the library: Download gosuperscript/monads library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
gosuperscript / monads example snippets
use function Superscript\Monads\Option\{Some, None};
// Create an Option
$some = Some(42);
$none = None();
// Check if value exists
$some->isSome(); // true
$none->isNone(); // true
// Transform the value
$doubled = Some(21)->map(fn($x) => $x * 2); // Some(42)
$empty = None()->map(fn($x) => $x * 2); // None
// Provide default values
Some(42)->unwrapOr(0); // 42
None()->unwrapOr(0); // 0
// Chain operations
Some(10)
->filter(fn($x) => $x > 5)
->map(fn($x) => $x * 2)
->unwrapOr(0); // 20
// Convert to Result
Some(42)->okOr("error"); // Ok(42)
None()->okOr("error"); // Err("error")
use function Superscript\Monads\Result\{Ok, Err};
function processData(array $data): Result {
return Ok($data)
->andThen(fn($d) => validateData($d))
->andThen(fn($d) => transformData($d))
->andThen(fn($d) => saveData($d));
}
$result = processData($input)->match(
err: fn($e) => response()->json(['error' => $e], 400),
ok: fn($d) => response()->json(['data' => $d], 200)
);
use Superscript\Monads\Result\Testing\ComparesResults;
use Superscript\Monads\Option\Testing\ComparesOptions;
class MyTest extends TestCase {
use ComparesResults;
use ComparesOptions;
public function test_example() {
// Custom assertions
$this->assertOk(Ok(42));
$this->assertErr(Err("error"));
$this->assertSome(Some(42));
$this->assertNone(None());
// PHPUnit constraints
$this->assertThat(Ok(42), $this->isOk());
$this->assertThat(Err("e"), $this->isErr());
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.