Skip to content

Functions are named procedures in Nim.

A function with no input parameters and no return values would look like:

proc main =             # "main" procedure (no inputs, no outputs)
  # Here starts the function body
  echo "Hello world"    

main                   # Here we are calling "main"; "main()" would be valid too

the function body is indented like in python

Returning values

When the proc returns a value we need to annotate its type:

proc getValue():int =
  #             ^^^ return type 
  var a = 50
  a = a + 20
  a += 10
  return a

echo getValue()

The following is equivalent:

proc getValue():int =
  50 + 20 + 10  # The last statement is returned; no need for `return` keyword

echo getValue()

and the following:

proc getValue():int = 50 + 20 + 10

echo getValue()

Input parameters

Input parameters need to be type annotated as well.

One input parameter and no returned value would be:

proc showValue(value:int) =
  #       param^^^^^ ^^^type
  echo "value: ", value

showValue(20)

Lets say we have two input parameters. We separate them using ;:

proc showNameAndAge(name:string; age:int) =
  #           param1^^^^^^^^^^^  ^^^^^^^param2
  echo "Name: ", name, " is ", age, " years old"

showNameAndAge("Ana", 50)

When there are several parameters of the same type, we separate them using ,:

proc showNameMinMax(name:string; min, max:int) =
  #                              ^^^^^^^^ two int params  
  echo "Name: ", name
  echo min, "<=", max

showNameMinMax("Ana", 10, 20)

input and output parameters

An example mixing input and output parameters:

proc sum(a,b: int): string = 
  return "Total: " & $(a+b)

echo sum(10,20)

and another:

proc sum(a,b: int): int = a + b

echo sum(10,20)

discard returned values

Whenever a procedure returns a value, it needs to be used. The following produces an error:

proc sum(a,b: int): int = a + b

sum(10,20)   # This will an error

You need to do something with the returned value:

proc sum(a,b: int): int = a + b

let value = sum(10,20) 

Or you can just do nothing:

proc sum(a,b: int): int = a + b

discard sum(10,20) 

Discarding a value might be useful when you are just interested in the side effects.

resultvariable

This is a special variable with the return type and whatever it holds will be returned.

proc example(val:int):int = 
  result = val + 20  #^^^this is the result's type
  echo "This is printed first"

echo example(10)
result shawdowing

If you define a variable named result within the function body it will shadow the special variable named result. So you won't get the expected behaviour:

proc example(val:int):int = 
  let result:int = val + 20  

echo example(10) # will print 0