Macros
macro `:=?`(a, b, body, elseBranch): untyped
-
Executes body if a := b doesn't fail any checks, otherwise executes elseBranch. body will be in the same scope as the definition a := b.
Uses break instead of exceptions for handling check failures unilke tryAssign. Due to Nim limitations, this means this cannot be used as an expression and must be a statement.
Example:
import options let a = some(3) some(n) :=? a: doAssert n == 3 else: doAssert false
Source Edit macro match(val: untyped; branches: varargs[untyped]): untyped
-
Naive pattern matching implementation based on :=?. Has the same limitation as :=?, which is that it cannot be used as an expression.
Example:
proc fizzbuzz(n: int): string = match (n mod 3, n mod 5): of (0, 0): result = "FizzBuzz" of (0, _): result = "Fizz" of (_, 0): result = "Buzz" else: result = $n for i in 1..100: echo fizzbuzz(i)
Source Edit macro matchInto(adr, val: untyped; branches: varargs[untyped]): untyped
-
Version of match which assigns the value of each branch body into adr. Uses language level assignment by default, and assign if ^ is used.
Example:
proc fizzbuzz(n: int): string = matchInto result, (n mod 3, n mod 5): of (0, 0): "FizzBuzz" of (0, _): "Fizz" of (_, 0): "Buzz" else: $n for i in 1..100: echo fizzbuzz(i)
Source Edit macro tryAssign(a, b): untyped
-
Version of tryAssign with an infix assignment as the first argument and no else block.
Example:
import options let a = some(3) tryAssign some(n) := a: # or = a doAssert n == 3
Source Edit macro tryAssign(a, b, body, elseBranch): untyped
-
Executes body if a := b doesn't fail any checks, otherwise executes elseBranch. body will be in the same scope as the definition a := b.
Uses exceptions instead of break unlike :=?. This allows it to be used as an expression but has a runtime cost.
Example:
import options let a = some(3) tryAssign some(n), a: doAssert n == 3 else: doAssert false
Source Edit macro tryMatch(val: untyped; branches: varargs[untyped]): untyped
-
Naive pattern matching implementation based on tryAssign. Has the same caveat of tryAssign, which is that it uses exceptions.
Example:
proc fizzbuzz(n: int): string = tryMatch (n mod 3, n mod 5): of (0, 0): "FizzBuzz" of (0, _): "Fizz" of (_, 0): "Buzz" else: $n for i in 1..100: echo fizzbuzz(i)
Source Edit macro unpackArgs(args, routine): untyped
-
Injects unpacking assignments into the body of a given routine.
Example:
proc foo(tup: (int, string)) {.unpackArgs: [(a, b): tup].} = doAssert a == b.len let t = (3, "abc") foo(t)
Source Edit
Templates
template `:=?`(a, b): bool
-
Executes (!) a := b and returns false if the checks in the assignment fail. Otherwise returns true. Note that the executed a := b will not have any affect on the scope of the following statements since it is in a block statement.
Example:
doAssert (a, b) :=? (1, 2) import options let a = none(int) doAssert not (some(n) :=? a)
Source Edit