Skip to content
Systems programming for what’s next.
— Vex

Operators -- Complete Reference ​

This page summarizes common operators, their source syntax and numeric behavior. Contract names in tables describe the conventional operation family; a user type needs an applicable operator callable. See operator methods for complete examples.

Arithmetic Operators ​

OperatorSyntaxContractDescription
Additiona + bAddElement-wise or numeric addition
Subtractiona - bSubElement-wise or numeric subtraction
Multiplicationa * bMulElement-wise or numeric multiplication
Divisiona / bDivElement-wise or numeric division
Moduloa % bModRemainder (integers) or element-wise modulo
Negation-aNegUnary minus
vex
let sum = 10 + 5          // 15
let diff = 10 - 5         // 5
let prod = 10 * 5         // 50
let quot = 10 / 3         // 3 (integer division)
let rem = 10 % 3          // 1
let neg = -42             // -42

// Floating point
let f_div = 10.0 / 3.0    // 3.333...

Scalar numeric operands and borrows ​

A primitive numeric borrow participates through its referent's value type: comparing an &i64 with zero is a signed numeric comparison, not an address comparison. Numeric widening preserves the source's signedness. Arithmetic uses its inferred result type; comparisons select a common numeric operand type before producing bool.

Mixed integer operands need a lossless implicit conversion to one operand's type. Integer/float operations use the existing numeric promotion to the selected float type. Required compile-time evaluation follows these same rules; this does not introduce an implicit float-to-integer conversion.

For a >> b, the value type of a determines arithmetic versus logical right shift. An unsigned shift count does not turn a signed value unsigned. Raw pointers are not implicitly loaded by these numeric rules.

Compound Assignment ​

OperatorEquivalent
a += ba = a + b
a -= ba = a - b
a *= ba = a * b
a /= ba = a / b
a %= ba = a % b
vex
let! x = 10
x += 5    // x = 15
x -= 3    // x = 12
x *= 2    // x = 24
x /= 4    // x = 6
x %= 4    // x = 2

Bitwise Operators ​

OperatorSyntaxContractDescription
ANDa & bBitAndBitwise AND
ORa | bBitOrBitwise OR
XORa ^ bBitXorBitwise XOR
NOT~aBitNotBitwise complement (unary)
Left Shifta << bShlShift left by b bits
Right Shifta >> bShrShift right by b bits
vex
let a: u8 = 0b1100_1010
let b: u8 = 0b1010_0110

let and_val = a & b     // 0b1000_0010
let or_val = a | b      // 0b1110_1110
let xor_val = a ^ b     // 0b0110_1100
let not_a = ~a          // 0b0011_0101

let shifted = a << 2    // 0b0010_1000 (left shift)
let right = a >> 3      // 0b0001_1001 (right shift)

Compound Bitwise Assignment ​

OperatorEquivalent
a &= ba = a & b
a |= ba = a | b
a ^= ba = a ^ b
a <<= ba = a << b
a >>= ba = a >> b

Comparison Operators ​

OperatorSyntaxContractDescription
Equala == bEqReturns true if equal
Not Equala != bEqReturns true if not equal
Less Thana < bOrdReturns true if a is less
Greater Thana > bOrdReturns true if a is greater
Less or Equala <= bOrdReturns true if a <= b
Greater or Equala >= bOrdReturns true if a >= b
vex
let same = (5 == 5)       // true
let diff = (5 != 3)       // true
let less = (3 < 5)        // true
let greater = (10 > 5)    // true
let le = (5 <= 5)         // true
let ge = (10 >= 5)        // true

Logical Operators ​

OperatorSyntaxContractDescription
ANDa && b—Short-circuit logical AND
ORa || b—Short-circuit logical OR
NOT!aNotLogical negation
vex
let t = true
let f = false

let and_val = t && f       // false (short-circuit: f not evaluated if t were false)
let or_val = t || f        // true
let not_val = !t           // false

// With &&, the right-hand expression is evaluated only if the left is true.

Short-circuit evaluation does not make raw pointer access safe: a non-null address may still be dangling, misaligned, uninitialized, or out of bounds. Raw reads need an unsafe context and a valid live pointee. See Memory Safety.

&& and || also accept &bool operands: they read the referenced boolean, not whether its address is non-null. Mixing bool and &bool preserves the same left-to-right, once-only evaluation and short-circuit rules, including inside #const:

vex
const fn both(left: &bool, right: &bool): bool {
    return left && right;
}

let enabled = false;
let ready = true;
let result = both(&enabled, &ready); // false

Binary operators automatically dereference one reference layer. For nested references, dereference the outer layer explicitly (for example, *left && *right for & &bool parameters). This does not grant logical operators an implicit raw-pointer dereference or change unary ! rules; use !*reference to negate a referenced boolean.

Indexing Operator ​

OperatorSyntaxContractDescription
Indexa[i]IndexElement access by index
vex
let arr = [10, 20, 30]
let second = arr[1]       // 20

let map = Map.new<string, i32>()
map["key"] = 42           // indexed assignment; distinct from a read
let val = map["key"]      // 42

Range Operators ​

OperatorSyntaxDescription
Exclusive Rangea..bFrom a (inclusive) to b (exclusive)
Inclusive Rangea..=bFrom a (inclusive) to b (inclusive)
Froma..From a to infinity
To Exclusive..bFrom start to b (exclusive)
To Inclusive..=bFrom start to b (inclusive)
Full Range..Everything
vex
for i in 0..5 { }          // 0, 1, 2, 3, 4
for i in 0..=5 { }         // 0, 1, 2, 3, 4, 5

let slice = data[1..4]     // elements at indices 1, 2, 3
let with_end = data[1..=4] // elements at indices 1, 2, 3, 4
let from_start = data[..3] // elements at indices 0, 1, 2
let to_end = data[2..]     // elements from index 2 to end

Reference and Pointer Operators ​

OperatorSyntaxDescription
Immutable Borrow&exprCreates an immutable reference
Mutable Borrow&expr!Creates a mutable reference
Dereference*exprDereferences a reference or pointer; raw-pointer access requires an unsafe context
vex
fn observe(counter: &i32!): bool {
    *counter = *counter + 1;
    return true;
}
fn main(): i32 {
    let x = 42;
    let ref_x: &i32 = &x;
    let! y = 10;
    let mut_ref: &i32! = &y!;
    *mut_ref = *mut_ref + 5;
    let! calls = 0;
    let result = false && observe(&calls!);
    if result || calls != 0 { return 1; }
    $println(*ref_x);
    $println(y);
    $println(calls);
    return 0;
}

Expected output is 42, 15, and 0, followed by exit status 0. The zero demonstrates that the right side of false && ... was not called.

Error Handling Operators ​

OperatorSyntaxDescription
Null-coalesceexpr ?? fallbackIf expr is None/Err, evaluates and returns fallback; otherwise returns the contained value
Rescueexpr !> fallbackIf expr is None/Err, returns fallback (lazy with ||, error-aware with |e|)
Tryexpr?Propagates None/Err from the enclosing function

Null-Coalescing Operator (??) ​

The right-hand expression is evaluated only if the left side is None or Err. A normal .or(fallback()) method call evaluates its argument before calling the method; .orElse takes a callback instead.

vex
let opt: Option<i32> = None
let val = opt ?? 0                     // 0

let res: Result<i32, string> = Err("fail")
let val = res ?? 42                    // 42

// expensiveFunction() runs only if opt is None:
let val = opt ?? expensiveFunction()

For a Result fallback that needs the error value, use the error-aware !> closure or orElse; ?? discards the error.

Rescue Operator (!>) ​

The !> operator extracts a value from Option<T> or Result<T,E>, providing a fallback on failure. The error value is passed to the fallback closure when recovering from Err.

Three Forms ​

vex
// 1. Direct value fallback (error DISCARDED):
let val = result !> 0

// 2. Lazy closure, error DISCARDED:
let val = result !> || computeDefault()

// 3. Lazy closure, error PASSED to closure:
let val = result !> |err| {
    $eprintln(f"Recovering from: {err}")
    fallbackFromError(err)
}

On Result<T,E> ​

vex
let res: Result<i32, i32> = Err(404)

// Error passed to closure -- |e| receives the 404
let val = res !> |err_code| {
    $println(f"Failed with code: {err_code}")
    err_code  // use error as fallback value
}
// val = 404

// Ok values pass through without calling closure
let ok: Result<i32, i32> = Ok(42)
let val = ok !> |e| {
    $println("Never called")
    0
}
// val = 42, closure not evaluated

On Option<T> ​

vex
let opt: Option<i32> = None

// Option uses || form (no error value to pass):
let val = opt !> || {
    $println("Was None, computing default")
    99
}
// val = 99

The fallback is only evaluated when the value is None/Err. This is the idiomatic Vex alternative to .unwrap() (which does not exist in Vex).

Try Operator (?) ​

Propagates errors from Option or Result:

vex
fn process(): Result<Data, Error> {
    let file = File.open("data.txt")?   // propagates Err
    let parsed = parse(file.readAll()?)?  // propagates Err
    return Ok(parsed)
}

Channel Operators ​

OperatorSyntaxDescription
Sendch <- valueMoves a value into the channel; blocks while full
Receive<-chBlocks for T; returns zero T when closed and drained
vex
let! ch = Channel.new<i32>(10)

ch <- 42                      // send value
let received = <-ch            // receive value (blocking)

// Select-like pattern with try operations
if let Some(val) = ch.tryRecv() {
    process(val)
}

Use recv(), recvResult(), or tryRecv() instead of <-ch when the program must distinguish a closed or not-ready channel from a valid zero value.

Ternary Operator ​

OperatorSyntaxDescription
Ternarycond ? a : bReturns a if cond is true, else b
vex
let max = a > b ? a : b
let status = code == 200 ? "OK" : "ERROR"

// Nested ternaries (use sparingly for readability)
let category = score >= 90 ? "A" :
               score >= 80 ? "B" :
               score >= 70 ? "C" : "F"

Type Operators ​

OperatorSyntaxDescription
Type Castexpr as TypeSafe or unsafe type conversion
Type Test(not in Vex)Use match or if let instead
vex
let x: i32 = 42
let y: f64 = x as f64      // safe: widening cast 42.0
let z: u8 = 300 as u8       // safe: truncating cast (wraps)

let ptr_val: Ptr<Opaque> = Ptr.null<Opaque>()
let addr: usize = ptr_val.addr()  // address-sized integer

SIMD-Specific Operators ​

Availability depends on element type, shape and lowering path. Fixed arrays have dedicated lowering; they do not all become owned tensors. See SIMD operations for numerical and backend limits.

SIMD Arithmetic ​

OperatorSyntaxDescription
Saturating Adda +| bAddition with saturation (clamp on overflow)
Saturating Suba -| bSubtraction with saturation
Saturating Mula *| bMultiplication with saturation
Mina <? bElement-wise minimum
Maxa >? bElement-wise maximum
Multiply-add tokena *+ bParser token; not a complete three-operand FMA recipe
Carry-less Multiplya *^ bCLMUL (cryptographic)
vex
let a = [100u8, 200u8, 50u8]
let b = [100u8, 100u8, 200u8]

let sat_add = a +| b     // [200, 255, 250] -- 200+100=300 clamped to 255
let sat_sub = a -| b     // [0, 100, 0]      -- 50-200=0 (clamped)
let min_vals = a <? b    // [100, 100, 50]
let max_vals = a >? b    // [100, 200, 200]

SIMD Rotation ​

OperatorSyntaxDescription
Rotate Lefta <<< bCircular left bit rotation
Rotate Righta >>> bCircular right bit rotation
vex
let x: u8 = 0b1000_0001
let rot_left = x <<< 1   // 0b0000_0011 (bit 7 wraps to bit 0)
let rot_right = x >>> 1  // 0b1100_0000 (bit 0 wraps to bit 7)

Horizontal Reductions (Prefix Operators) ​

Reductions collapse lanes to a scalar. Use the prefix reduction forms:

OperatorSyntaxDescription
Sum<+ valuesAdd lanes
Product<* valuesMultiply lanes
AND<& valuesBitwise/logical AND
OR<|> valuesBitwise/logical OR
Minimum<?| valuesMinimum lane
Maximum>?| valuesMaximum lane
vex
let values: [i32; 4] = [1, 2, 3, 4];
let total = <+ values;   // 10
let product = <* values; // 24

Floating-point accumulation order, empty inputs and special values need the operation's actual contract. A parallel reduction need not reproduce the low bits of a sequential loop.

Matrix Operations ​

OperatorSyntaxIntended operation
Matrix multiplya <*> bMultiply compatible matrix shapes
Matrix powera <^> nRepeated square-matrix multiplication
Linear solvea <\> bSolve a linear system on a supporting route

A flat [f64; 4] does not declare a 2×2 matrix. The operation requires shape information or an explicit overload that defines it. Parser recognition does not prove support for arbitrary rank, dtype or backend. Use the shape and matrix guidance before relying on these forms.

Operator Precedence ​

The table follows the parser's infix binding powers, strongest first. Postfix call/index/member access, prefix unary operations and casts are handled separately; parenthesize mixed forms when the intended grouping is not obvious.

GroupOperators
Castas
Powers** (right-associative), then <^>
Multiplicative*, /, %, *|, *^, *+
Additive+, -, +|, -|
Concatenation++
Shift/rotate<<, >>, <<<, >>>
Bitwise AND, XOR, OR&, then ^, then |
Coalescing??
Relational/min/max<, <=, >, >=, <?, >?
Equality==, !=
Logical AND, OR&&, then ||
Matrix multiply/solve<*>, <\>
Ranges.., ..=
Pipelines|>, <|
Assignment/send=, compound assignment, <- (right-associative)
Rescue!>
Ternarycondition ? yes : no

For example, x & 1 == 1 groups as (x & 1) == 1, and a ?? b + 1 groups as a ?? (b + 1). Prefix reduction operands should be parenthesized when reducing an expression: <+ (a * b).

Best Practices ​

  1. Use parentheses to clarify precedence in complex expressions, even when you know the rules.
  2. Prefer if/else over nested ternary operators for readability.
  3. Use compound assignment operators (+=, *=, etc.) for concise mutation.
  4. For SIMD operations, inspect the emitted route when vectorization matters.
  5. When overloading operators, define domain-appropriate laws; concatenation is a useful noncommutative +.
  6. Implement Eq and Ord as a pair when your type has a natural ordering.

Released under the MIT License.