Add bind() to option and result

This commit is contained in:
2024-07-28 22:50:59 -04:00
parent efb3a4461e
commit 57af645d87
5 changed files with 89 additions and 8 deletions

View File

@@ -93,6 +93,21 @@ readonly class Option
return $this->value ?? $f();
}
/**
* Bind a function to this option (railway processing)
*
* If this option is Some, the function will be called with the option's value. If this option is None, it will be
* immediately returned.
*
* @template TBound The type returned by Some in the bound function
* @param callable(T): Option<TBound> $f The function that will receive the Some value; can return a different type
* @return Option<TBound> The updated option if the starting value was Some, None otherwise
*/
public function bind(callable $f): Option
{
return $this->isNone() ? $this : $f($this->get());
}
/**
* Map this optional value to another value
*