Do notation

As a special convenience notation that keeps most elements of a regular proc expression, the do keyword can be used to pass anonymous procedures to routines:

  1. var cities = @["Frankfurt", "Tokyo", "New York", "Kyiv"]
  2. sort(cities) do (x, y: string) -> int:
  3. cmp(x.len, y.len)
  4. # Less parentheses using the method plus command syntax:
  5. cities = cities.map do (x: string) -> string:
  6. "City of " & x

do is written after the parentheses enclosing the regular proc parameters. The proc expression represented by the do block is appended to the routine call as the last argument. In calls using the command syntax, the do block will bind to the immediately preceding expression rather than the command call.

do with a parameter list or pragma list corresponds to an anonymous proc, however do without parameters or pragmas is treated as a normal statement list. This allows macros to receive both indented statement lists as an argument in inline calls, as well as a direct mirror of Nim’s routine syntax.

  1. # Passing a statement list to an inline macro:
  2. macroResults.add quote do:
  3. if not `ex`:
  4. echo `info`, ": Check failed: ", `expString`
  5. # Processing a routine definition in a macro:
  6. rpc(router, "add") do (a, b: int) -> int:
  7. result = a + b