Unit in Phunkie represents a type with exactly one value, similar to void in other languages but as a proper type. It’s often used to represent the absence of a meaningful value while maintaining type safety.
Unit is a singleton type where all instances are equal, and it forms a trivial monoid where combining any two Units always produces Unit.
There’s only one way to create a Unit value, as it only has one possible value:
// Create a Unit value
$unit = Unit();
// Unit is also an empty tuple
$unit = Tuple(); // same as Unit()
Unit has several special properties:
$unit = Unit();
// String representation
echo $unit->toString(); // "()"
// Type representation
echo $unit->showType(); // "Unit"
// Cannot access members
$unit->_1; // Throws Error: _1 is not a member of Unit
// Cannot modify
$unit->_1 = 42; // Throws Error: _1 is not a member of Unit
// Cannot copy
$unit->copy(['1' => 42]); // Throws Error: copy is not a member of Unit
All Unit values are equal to each other, as Unit is a singleton type:
$unit1 = Unit();
$unit2 = Unit();
$unit1->eqv($unit2); // true - all Units are equal
The equality satisfies all the Eq laws:
x->eqv(x) is always truex->eqv(y) equals y->eqv(x)x->eqv(y) and y->eqv(z), then x->eqv(z)Unit forms a trivial monoid where:
$unit = Unit();
// Get the zero (identity) element
$zero = $unit->zero(); // Unit()
// Combine two Units
$combined = $unit->combine(Unit()); // Unit()
// Monoid laws are satisfied:
// Left identity: zero()->combine(x) == x
$unit->zero()->combine($unit)->eqv($unit); // true
// Right identity: x->combine(zero()) == x
$unit->combine($unit->zero())->eqv($unit); // true
// Associativity: (a->combine(b))->combine(c) == a->combine(b->combine(c))
$a = Unit();
$b = Unit();
$c = Unit();
$a->combine($b)->combine($c)->eqv($a->combine($b->combine($c))); // true
Unit is useful in several scenarios:
function log($message) {
echo $message . "\n";
return Unit();
}
Option(Unit()); // Some(Unit) or None
Either(Unit(), $value); // Left(Unit) or Right($value)
// Unit is useful when you need a neutral element
$result = $list->foldLeft(Unit(), fn($acc, $x) => {
performSideEffect($x);
return Unit();
});
null or void when you need to represent the absence of a value