I was reading this post by @vry and encountered this cute expression:
repeat { $0 + 1 }(each t)
Could anyone explain what this expression does for the benefit of the learners?
I could make an attempt, but I don't feel qualified yet.
Thank you
I was reading this post by @vry and encountered this cute expression:
repeat { $0 + 1 }(each t)
Could anyone explain what this expression does for the benefit of the learners?
I could make an attempt, but I don't feel qualified yet.
Thank you
It calls a function on each element of a parameter pack, and creates a new pack containing the return values of those function calls.
The input pack is named t
.
The body of the function is the closure expression { $0 + 1 }
, which adds 1 to its input and returns the result. This uses the shorthand $0
for the first argument to an anonymous function, and also elides the return
keyword because there is only a single line of code within the function body.
The parentheses are โfunction callโ parentheses, and they contain within them the arguments to the function. Here there is one argument, namely โeach t
โ, which represents the individual elements of a parameter pack.
The โrepeat
โ at the start of the line indicates that this is done for every element in the pack, and the results are collected into a new pack.
What @Nevin said, and also, recall that in general, { f($0) }(x)
is the same as f(x)
, so your expression is the same as repeat (each t + 1)
.