Search code examples
tuplesapplynim-lang

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?

Solution

  • 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.