Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tuple to function arguments in Nim

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?
like image 999
Imran Avatar asked Jan 24 '18 08:01

Imran


People also ask

Can you pass tuples as arguments for a function?

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.

Which function takes tuple as argument?

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.


1 Answers

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.

like image 75
def- Avatar answered Oct 14 '22 06:10

def-