W3cubDocs

/Nim

Module sugar

This module implements nice syntactic sugar based on Nim's macro system.

Imports

macros

Vars

lc: ListComprehension

Macros

macro `=>`(p, b: untyped): untyped
Syntax sugar for anonymous procedures.
proc passTwoAndTwo(f: (int, int) -> int): int =
  f(2, 2)

passTwoAndTwo((x, y) => x + y) # 4
macro `->`(p, b: untyped): untyped
Syntax sugar for procedure types.
proc pass2(f: (float, float) -> float): float =
  f(2, 2)

# is the same as:

proc pass2(f: proc (x, y: float): float): float =
  f(2, 2)
macro `[]`(lc: ListComprehension; comp, typ: untyped): untyped
List comprehension, returns a sequence. comp is the actual list comprehension, for example x | (x <- 1..10, x mod 2 == 0). typ is the type that will be stored inside the result seq.
echo lc[x | (x <- 1..10, x mod 2 == 0), int]

const n = 20
echo lc[(x,y,z) | (x <- 1..n, y <- x..n, z <- y..n, x*x + y*y == z*z),
        tuple[a,b,c: int]]
macro dump(x: typed): untyped

Dumps the content of an expression, useful for debugging. It accepts any expression and prints a textual representation of the tree representing the expression - as it would appear in source code - together with the value of the expression.

As an example,

let
  x = 10
  y = 20
dump(x + y)

will print x + y = 30.

macro distinctBase(T: typedesc): untyped
reverses type T = distinct A; works recursively.

Examples:

type
  T = distinct int
doAssert distinctBase(T) is int
doAssert:
  not compiles(distinctBase(int))
type
  T2 = distinct T
doAssert distinctBase(T2) is int

© 2006–2018 Andreas Rumpf
Licensed under the MIT License.
https://nim-lang.org/docs/sugar.html