Can I convert a tuple into a list of function arguments in Nim? In other languages this is known as "splat" or "apply".
For example:
proc foo(x: int, y: int) = echo("Yes you can!")
type:
Point = tuple[x, y: int]
let p: Point = (1,1)
# How to call foo with arguments list p?
A tuple can also be passed as a single argument to the function. Individual tuples as arguments are just individual variables. A function call is not an assignment statement; it's a reference mapping.
A tuple can be an argument, but only one - it's just a variable of type tuple . In short, functions are built in such a way that they take an arbitrary number of arguments. The * and ** operators are able to unpack tuples/lists/dicts into arguments on one end, and pack them on the other end.
I haven't seen this in the stdlib or any other lib, but you can certainly do it yourself with a macro:
import macros
macro apply(f, t: typed): typed =
var args = newSeq[NimNode]()
let ty = getTypeImpl(t)
assert(ty.typeKind == ntyTuple)
for child in ty:
expectKind(child, nnkIdentDefs)
args.add(newDotExpr(t, child[0]))
result = newCall(f, args)
proc foo(x: int, y: int) = echo("Yes you can!")
type Point = tuple[x, y: int]
let p: Point = (1,1)
# How to call foo with arguments list p?
apply(foo, p) # or:
foo.apply(p)
Further testing would be required to make sure this works with nested tuples, objects etc. You also might want to store the parameter in a temporary variable to prevent side effects from calling it multiple times to get each tuple member.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With