元组在Nim中的函数参数

时间:2018-01-24 08:57:23

标签: tuples apply nim

我可以将元组转换为Nim中的函数参数列表吗?在其他语言中,这被称为“splat”或“apply”。

例如:

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?

1 个答案:

答案 0 :(得分:3)

我没有在stdlib或任何其他lib中看到过这个,但你可以用宏来自己做:

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)

需要进一步测试以确保它适用于嵌套元组,对象等。您还可能希望将参数存储在临时变量中,以防止副作用多次调用它来获取每个元组成员。

相关问题