Procedures

7.1 Defining Procedures

proc add(a: int, b: int): int =
  return a + b

proc add2(a, b: int): int = a + b          # last expression is the return value

proc greet(name: string, greeting = "Hello") =   # default parameter
  echo greeting, ", ", name

greet("Ana")
greet("Ana", greeting = "Hi")              # named argument

7.2 The result Variable

proc sumTo(n: int): int =
  for i in 1..n:
    result += i        # implicit `result`, initialized to the default value

7.3 var Parameters (Pass by Reference)

Parameters are immutable by default. Large values are passed by hidden pointer automatically (efficient).

proc increment(x: var int, by = 1) = x += by
var c = 5
increment(c)
echo c   # 6

7.4 func (No Side Effects)

func square(x: int): int = x * x     # equivalent to proc with {.noSideEffect.}

7.5 Overloading

proc show(x: int) = echo "int: ", x
proc show(x: string) = echo "string: ", x
proc show(x: float) = echo "float: ", x

7.6 Varargs and Open Arrays

proc sumAll(nums: varargs[int]): int =
  for n in nums: result += n
echo sumAll(1, 2, 3)

proc printAll(items: varargs[string, `$`]) =   # converts each arg with `$`
  for it in items: stdout.write it, " "
printAll(1, "two", 3.0)

7.7 Forward Declarations and Recursion

proc isEven(n: int): bool
proc isOdd(n: int): bool = (if n == 0: false else: isEven(n - 1))
proc isEven(n: int): bool = (if n == 0: true else: isOdd(n - 1))

proc fact(n: int): int = (if n <= 1: 1 else: n * fact(n - 1))

7.8 Returning Multiple Values

proc divmod(a, b: int): (int, int) = (a div b, a mod b)
let (q, r) = divmod(17, 5)

proc minMax(s: seq[int]): tuple[lo, hi: int] =
  result = (s.min, s.max)
echo minMax(@[3, 1, 9]).hi

7.9 Procedure Types and Calling Conventions

Calling conventions: nimcall (default), closure, cdecl, stdcall, inline, fastcall, noconv.

type BinOp = proc (a, b: int): int {.nimcall.}
proc apply(f: BinOp, x, y: int): int = f(x, y)
echo apply(add2, 2, 3)

7.10 Exporting

The * suffix exports a symbol from a module: proc publicApi*() = ..., type Point* = object.