https://nim-lang.org/docs/tut3.html#introduction-code-blocks-as-arguments
echo "Hello ":
let a = "Wor"
let b = "ld!"
a & b
It is possible to pass the last argument of a call expression in a separate code block with indentation. For example, the following code example is a valid (but not a recommended) way to call echo:
I really don't know how to understand this code and the text, how is a & b called?
I really don't know how to understand this code and the text, how is a & b called?
& concats two strings, here a and b. Same as echo a,b
The code-block gets executed and should print "Hello World!"
It is possible to pass the last argument of a call expression in a separate code block with indentation. For example, the following code example is a valid (but not a recommended) way to call echo.
echo "Hello ": is the same as echo("Hello", foo), where foo is the result of the evaluation of the following block expression:
block:
let a = "Wor"
let b = "ld!"
a & b
Which is an alternative to the following:
(let a = "Wor"; let b = "ld!"; a & b)
Both these expressions evaluate the same.
a & b is the same as `&`(a, b) or a.`&`(b)
In this code example there are 2 concepts combined together:
1. indented code block after : is evaluated and passed as the last argument to the procedure:
proc foo(a, b: int) =
echo "first argument is " & $a
echo "second argument is " & $b
foo 144: # first argument is 144
2 + 3 # second argument is 5
Essentialy, nim transforms this call to foo(144, 2+3).
2. When code block is evaluated, only the last statement is considered:
let a = block:
var tmp = newSeq[int](5) # destroyed at the end of scope
for i, _ in tmp:
tmp[i] = i
tmp # only this line is assigned to variable `a`
# you can do same thing with parentheses
let b = (echo "123"; 14)
# ^ only the last statement is assigned to `b`
echo a # @[0, 1, 2, 3, 4]
echo b # 14