Type ‣ Error union ᴾᴴᴾ - chung-leong/zigar GitHub Wiki

JavaScript | PHP


An error union holds either a value or an error. In normal usage you'll not encounter standalone error-union objects. Upon access they would be resolved automatically, either producing their assigned values or causing errors to be thrown:

const MathError = error{negative_number};
pub fn getSquareRoot(number: f64) MathError!f64 {
    if (number < 0) {
        return MathError.NegativeNumber;
    }
    return @sqrt(number);
}
<?php

$m = zigar_use(__DIR__ . '/error-union-example-1.zig');

try {   
    echo "sqrt(36) = " . $m->getSquareRoot(36) . "\n";
    echo "sqrt(-36) = " . $m->getSquareRoot(-36) . "\n";
} catch (Exception $e) {
    echo $e->getMessage(), "\n";
}
sqrt(36) = 6
negative number

Error-union arrays

It's possible to have an array of error unions, each representing the outcome of an individual operation:

const std = @import("std");

const MathError = error{negative_number};

pub fn getSquareRoots(allocator: std.mem.Allocator, numbers: []const f64) ![]MathError!f64 {
    const results = try allocator.alloc(MathError!f64, numbers.len);
    for (numbers, results) |number, *result_ptr| {
        result_ptr.* = if (number >= 0) @sqrt(number) else MathError.negative_number;
    }
    return results;
}
<?php

$m = zigar_use(__DIR__ . '/error-union-example-2.zig');

$numbers = [ 1, 2, 3, -4, 5 ];
try {
    $sqrts = $m->getSquareRoots($numbers);
    foreach ($sqrts as $index => $sqrt) {
        $number = $numbers[$index];
        echo "sqrt($number) = $sqrt\n";
    }
} catch (Exception $e) {
    echo $e->getMessage(), "\n";
}
sqrt(1) = 1
sqrt(2) = 1.4142135623731
sqrt(3) = 1.7320508075689
negative_number

The return type of getSquareRoots() might look a little odd with its two exclamation marks. It is an error union of an array of error unions. The outer error union captures potential out-of-memory error during allocation of the result array. The array itself captures errors of the individual square-rooting operations. When we loop through the results, we are able to process the first three numbers. The fourth number causes an exception, terminating the loop.


Types | Error set