Nim, lesson 6
As a program grows, you want to give a piece of logic a name, reuse it, and test it on its own.
Nim calls these procedures, declared with proc.
Every parameter has a type, and the type after the closing parenthesis is the return type.
The body is indented after =. When the body's last expression has the right type, that is the
value the procedure returns. Parameters of the same type can share it: (price, quantity: int).
Nim gives every procedure with a return type an implicit variable called result, already set to
the type's default (0 for int, false for bool, "" for string). Whatever holds
at the end is returned:
2 exercises to try what you just read.
resultYou can also use return value to leave a procedure immediately, which is handy for early exits:
Nim does not let you silently ignore a returned value. If you call a procedure only for its side
effect, write discard total(4, 3) to say so on purpose.
funcfunc is a proc that promises not to have side effects: no printing, no reading input, no
changing global variables. It just turns inputs into an output. The compiler checks the promise.
Use func for pure calculations; it makes clear which parts of your program touch the outside
world.
Thanks to Nim's method call syntax, square(5) can also be written 5.square() or even
5.square. The first argument moves in front of the dot. That is why stdin.readLine() and
readLine(stdin) mean the same thing.
Parameters and variables declared inside a procedure exist only inside it. A procedure can read top-level variables declared above it, but relying on that makes code harder to follow. Prefer passing everything a procedure needs as parameters. Parameters are read-only inside the body: to change a number, compute a new value and return it.
Write func isPrime(n: int): bool, which returns true when a number is prime (it has exactly
two divisors, 1 and itself) and false otherwise. Numbers below 2 are not prime.
Try divisors d = 2, 3, 4, ... while d * d <= n, and return false as soon as one divides
n evenly.
Input: one whole number. Output: N is prime or N is not prime.
prints 97 is prime.
A speaker's volume must stay between a lowest and a highest setting. Write
func clamp(value, low, high: int): int, which returns:
low if the value is below low,high if the value is above high,Input: three lines: the requested value, then low, then high (low is never above
high). Output: the clamped value.
proc total(price: int, quantity: int): int =
price * quantity
echo total(4, 3) # 12proc sumUpTo(n: int): int =
for i in 1..n:
result += i
echo sumUpTo(4) # 10proc describe(age: int): string =
if age < 0:
return "not born yet"
if age < 18:
return "minor"
"adult"func square(x: int): int = x * x97