Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add: Monad interface and Option types. #5

Merged
merged 1 commit into from
May 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions src/Monad.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

declare(strict_types=1);

namespace EndouMame\PhpMonad;

use Closure;

/**
* @template T
*/
interface Monad
{
/**
* @template T2
* @param Closure(T):static<T2> $f
* @return static<T2>
*/
public function bind(Closure $f): self;

/**
* @template TValue
* @param TValue $value
* @return static<TValue>
*/
public static function unit(mixed $value): self;
}
24 changes: 24 additions & 0 deletions src/Option.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

declare(strict_types=1);

namespace EndouMame\PhpMonad;

use EndouMame\PhpMonad\Option\Some;

/**
* @template T
* @implements Monad<T>
*/
abstract class Option implements Monad
{
/**
* @template TValue
* @param TValue $value
* @return Option<TValue>
*/
public static function unit(mixed $value): self
{
return new Some($value);
}
}
48 changes: 48 additions & 0 deletions src/Option/None.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

declare(strict_types=1);

namespace EndouMame\PhpMonad\Option;

use Closure;
use EndouMame\PhpMonad\Option;
use Override;

/**
* @template T
* @extends Option<T>
*/
final class None extends Option
{
/**
* @param T $value
*/
public function __construct(protected mixed $value)
{
}

/**
* @template T2
* @param Closure(T): static<T2> $f
* @return static<T2>
*/
#[Override]
public function bind(Closure $f): self
{
/** @var T2 */
$v = null;

return self::unit($v);
}

/**
* @template TValue
* @param TValue $value
* @return None<TValue>
*/
#[Override]
public static function unit(mixed $value): self
{
return new self($value);
}
}
33 changes: 33 additions & 0 deletions src/Option/Some.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

declare(strict_types=1);

namespace EndouMame\PhpMonad\Option;

use Closure;
use EndouMame\PhpMonad\Option;
use Override;

/**
* @template T
* @extends Option<T>
*/
final class Some extends Option
{
/**
* @param T $value
*/
public function __construct(protected mixed $value)
{
}

/**
* @param Closure(T): static<T> $f
* @return static<T>
*/
#[Override]
public function bind(Closure $f): self
{
return $f($this->value);
}
}
Loading