Operators and Expressions

5.1 Operators

+ - * / div mod (/ always returns float, div is integer division) and or not xor (also bitwise on ints)

and or xor not shl shr (ashr for arithmetic shift) &, &=, add Identity / type is, isnot, of

.. (inclusive), ..< (exclusive), ^1 (backwards index)

echo 7 div 2, " ", 7 mod 2, " ", 7 / 2    # 3 1 3.5
echo 5 in 1..10                           # true
echo "a" & "b"

5.2 Custom Operators

Precedence is determined by the operator's first character (and *// etc.). Operators ending in = (except comparisons) are assignment-like.

proc `+`(a, b: Vec2): Vec2 = Vec2(x: a.x + b.x, y: a.y + b.y)
proc `$`(v: Vec2): string = "(" & $v.x & ", " & $v.y & ")"
proc `[]`(m: Matrix, i, j: int): float = m.data[i * m.cols + j]
proc `[]=`(m: var Matrix, i, j: int, val: float) = m.data[i * m.cols + j] = val
proc `<=>`(a, b: int): int = cmp(a, b)    # any sequence of operator chars

5.3 Everything Is an Expression (Mostly)

let grade = if score >= 90: "A" elif score >= 80: "B" else: "C"
let kind = case n
  of 0: "zero"
  of 1..9: "small"
  else: "large"
let v = block:
  let t = compute()
  t * 2

5.4 Method Call Syntax (UFCS) and Command Syntax

proc double(x: int): int = x * 2
echo double(5)      # normal
echo 5.double()     # method call syntax
echo 5.double       # parentheses optional
echo double 5       # command syntax
"hello".toUpperAscii.echo