santa
santa

Reputation: 1003

Idiomatic way for single-expressions procs in nim

Why do I see

proc simple(a, b: int) : int =
  result = a + b

so often in nim code when it seems as if

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

would suffice? Is there any semantic difference between those two that I'm missing?

The only reference to implicitly returning the last statement I found on nim-lang wasn't in the manual but in the tut where it states that

[...] a proc's body can consist of a single expression whose value is then returned implicitly.

Which seems misleading: it seems as it works for every 'last expression' (unless result was already set, then the result of the statement has to be discarded)

Upvotes: 0

Views: 289

Answers (2)

xbello
xbello

Reputation: 7443

In the coding conventions (https://nim-lang.org/docs/nep1.html#introduction-coding-conventions) they recommend to use return only if it's needed in the flow.

The book Nim in Action says 'it's not idiomatic to use the return keyword as the last statement of the proc', but it's not explicit about result = a + b vs a + b. From the snippets around the book, the convention seems to be:

  • Prefer a + b.
  • Use result = a + b only if you are modifying result, as in result.add(b).
  • Use return a only to do an early exit from the proc.

The book also list this gotcha that won't compile:

proc resultVar: string = 
  result = "The result"
  "This cause an error"

The reason behind code like result = a + b or return a is that people can't get all the idiomatics, specially when they are beginners like me. I still see for i in range(len(variable)) in Python code, which is not only non-pythonic but ugly and underperformant.

Upvotes: 3

juj
juj

Reputation: 447

One of the more exotic features is the implicit result variable: every procedure in Nim with a non-void return type has an implicit result variable that represents the value that will be returned [Wikipedia].

Upvotes: 0

Related Questions