Options in Phunkie represent optional values. An Option type can either be Some(value)
containing a value, or None
representing the absence of a value. This is a safer alternative to using null values in your code.
There are several ways to create Options:
// Using the Option constructor function
$some = Option(42); // Some(42)
$none = Option(null); // None
// Using explicit constructors
$some = Some(42); // Some(42)
$none = None(); // None
Options provide several basic operations:
$option = Option(42);
// Check if value exists
$option->isDefined(); // true for Some, false for None
$option->isEmpty(); // false for Some, true for None
// Get value with fallback
$option->getOrElse(0); // returns the value or the fallback if None
Options implement several type classes that provide powerful functional operations:
$option = Option(2);
$result = $option->map(fn($x) => $x * 2); // Some(4)
$none = None();
$result = $none->map(fn($x) => $x * 2); // None
$option = Option(42);
$result = $option->filter(fn($x) => $x > 40); // Some(42)
$result = $option->filter(fn($x) => $x < 40); // None
$value = Option(1);
$function = Option(fn($x) => $x + 1);
$result = $value->apply($function); // Some(2)
$option = Option(2);
$result = $option->flatMap(fn($x) => Option($x * 2)); // Some(4)
$option = Option(42);
$result = $option->fold(
0, // Initial value if None
fn($x) => $x * 2 // Function to apply if Some
);
Options can be used in pattern matching:
$result = match(true) {
$option instanceof Some => "Got value: " . $option->get(),
$option instanceof None => "No value",
};
Options provide utility functions for working with lists:
use function Phunkie\Functions\option\listToOption;
use function Phunkie\Functions\option\optionToList;
$list = ImmList(1);
$option = listToOption($list); // Some(1)
$backToList = optionToList($option); // ImmList(1)
Options are type-safe and maintain their type information throughout operations. They implement the Kind
interface and support higher-kinded types in Phunkie.
getOrElse()
when you need to extract the value with a fallbackOptions satisfy several important laws:
These laws ensure that Options behave consistently and predictably in your code.