Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 36 ยท Procedures and Control Flow

Procedures: proc, func and result

Define procedures in Nim with proc and func, return values with result and return, use default and named arguments, discard results, forward declarations, with C stand-ins.

A procedure is a named block of code that you can call again and again. In Nim they are introduced with proc (or func, for procedures without side effects). If you know functions from Python or C, procedures will feel natural, with a few Nim-flavored touches: the special result variable, implicit returns, and a rule that you must not silently ignore a value.

Nim snippets are read-only here; C stand-ins that run on the page mirror the ideas.

A first procedure

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

echo add(3, 4)         # 7

The pieces: the name add, parameters a, b: int (both integers), the return type : int, an = sign, and an indented body. Parameter lists group names that share a type, as in proc area(width, height: float): float.

The compiler infers nothing about the return type, so you must write it unless the procedure returns nothing.

Returning values: the three ways

1. return: leave immediately with a value.

2. The last expression: if the final expression of a procedure has a value, it is returned.

NIM
proc square(x: int): int =
  x * x

3. The result variable: every procedure with a return type has an automatic variable called result, initialized to the type's default. Fill it in and it is returned when the body ends.

NIM
proc sumTo(n: int): int =
  for i in 1 .. n:
    result += i        # result starts at 0

echo sumTo(10)         # 55

Using result avoids a separate local variable and is the idiom for building up a value, for example a seq or string:

NIM
proc repeatText(s: string, times: int): string =
  for _ in 1 .. times:
    result.add s

return with no value inside such a procedure returns the current result. Mixing return x with result is allowed but pick one style per procedure.

Procedures without a result

NIM
proc greet(name: string) =
  echo "Hello, ", name, "!"

greet("Ada")

With no return type the procedure returns nothing (void). Such procedures usually exist for their side effects: printing, writing files, changing state.

func: procedures without side effects

NIM
func average(a, b: float): float =
  (a + b) / 2

func is a proc that the compiler checks is pure: it may not touch global mutable state, print, or call procedures that do. The restriction makes the code easier to reason about and test. echo inside a func is rejected (use debugEcho while debugging). Use func by default and proc when you need effects.

Keyword May have side effects? Typical use
func no (checked) calculations, conversions, predicates
proc yes I/O, mutation, anything else

Default and named arguments

NIM
proc connect(host: string, port = 8080, secure = false): string =
  let scheme = if secure: "https" else: "http"
  scheme & "://" & host & ":" & $port

echo connect("example.com")
echo connect("example.com", 443, true)
echo connect("example.com", secure = true)

Parameters with defaults can be left out. Named arguments (secure = true) let you skip earlier defaults and make calls readable. The first call prints http://example.com:8080, and the last prints https://example.com:8080.

discard

Nim insists you do something with a returned value:

NIM
proc log(msg: string): int =
  echo msg
  result = msg.len

log("hi")              # error: expression has to be used or discarded
discard log("hi")      # fine: explicitly ignored

The rule catches mistakes such as forgetting to use findIndex(...). For a procedure whose result is rarely needed, mark it {.discardable.}.

Forward declarations and nesting

Procedures must be known before use, unless you declare them first:

NIM
proc isEven(n: int): bool      # forward declaration, no body yet

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)

You can also nest a procedure inside another one. The inner procedure can read the outer one's variables, which leads to closures (coming up).

Stand-in: returning values in C

C functions return a value with return; there is no automatic result, so this stand-in shows the equivalent by declaring a local and returning it. A pointer parameter plays the role of an output.

C Stand-in: result-style accumulation and defaults

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Stand-in: an ignored result

Forgetting a result is a C bug that the compiler can warn about, and a thing Nim forbids. This stand-in shows how to ignore it on purpose.

C Stand-in: explicitly ignoring a result

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The (void) cast in C and discard in Nim say the same thing: "I know there is a result, and I do not need it."

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is result in a Nim procedure that returns a value?

    result is declared for you with the return type's default value and returned when the body ends.
  2. 2. What distinguishes func from proc?

    func is a pure procedure; touching globals or printing is a compile error.
  3. 3. What must you do with an unused return value?

    Nim refuses to silently ignore a result; discard makes it explicit.
  4. 4. Given proc connect(host: string, port = 8080, secure = false), which call is valid?

    host has no default, so it is required; named arguments can skip port.

Summary

  • proc name(params): Type = body defines a procedure; the last expression, return or result supplies the value.
  • func is a procedure checked for purity; prefer it when you can.
  • Default and named arguments make calls flexible; unused results need discard.
  • Forward declarations allow mutual recursion; procedures can be nested.

Next: Parameters, overloading and UFCS