【问题标题】:Can I unpack `varargs` to use as individual procedure call arguments with nim?我可以解压 `varargs` 以使用 nim 作为单独的过程调用参数吗?
【发布时间】:2021-06-29 23:22:48
【问题描述】:

我需要从过程的输入中解压缩varargs 以用作过程的各个参数..

在 python 中,您可以像这样“解压”函数调用的参数列表:

def fun(a, b, c, d):
    print(a, b, c, d)
 
my_list = [1, 2, 3, 4]
 
# Unpacking list into four arguments
fun(*my_list)  # asterisk does the unpacking

因此列表中的每个项目都用作函数调用中的单独参数。

这可以在 nim 中完成吗?我知道您可以使用varargs 接受任意数量的过程参数,但我想从varargs 解压缩参数序列,以将它们用作不接受varargs 的不同过程调用的单独参数。

假设我正在尝试解压缩一系列参数以创建一个可以运行任意过程(带有任意数量的参数)的过程,并告诉用户运行所述过程需要多长时间。我不想编写所有程序来接受 varargs 类型,因此如果可能的话,解压序列将是最好的解决方案。

import times


proc timeit*[T] (the_func: proc, passed_args: varargs[T]): float =
    let t = cpuTime()
    var the_results = the_func(passed_args)  # This is where I need to unpack arguments
    cpuTime() - t


proc test_func(x: int, y: int): int =
    x + y


echo timeit(test_func, 15, 5)

我知道这段代码不正确,而且我对 nim 很陌生,所以我很难找到正确的方法。

【问题讨论】:

  • 我使用unpackVarargs更新了我的答案。

标签: nim-lang


【解决方案1】:

macros 标准库中查看unpackVarargs

import std/[times, macros]

template timeIt*(theFunc: proc, passedArgs: varargs[typed]): float =
  let t = cpuTime()
  echo unpackVarargs(theFunc, passedArgs)
  cpuTime() - t

proc add2(arg1, arg2: int): int =
  result = arg1 + arg2

proc add3(arg1, arg2, arg3: float): float =
  result = arg1 + arg2 + arg3

echo timeIt(add2, 15, 5)
echo timeIt(add3, 15.5, 123.12, 10.009)

https://play.nim-lang.org/#ix=3rwD


这是一个甚至不需要unpackVarargs 的替代答案(来源:GitHub @timotheecour)。它使用varargs[untyped]timeIt 模板中键入:

import std/[times]

template timeIt*(theFunc: proc, passedArgs: varargs[untyped]): float =
  let t = cpuTime()
  echo theFunc(passedArgs)
  cpuTime() - t

proc add2(arg1, arg2: int): int =
  result = arg1 + arg2

proc add3(arg1, arg2, arg3: float): float =
  result = arg1 + arg2 + arg3

echo timeIt(add2, 15, 5)
echo timeIt(add3, 15.5, 123.12, 10.009)

https://play.nim-lang.org/#ix=3rwM

【讨论】:

    猜你喜欢
    • 2013-09-15
    • 2015-12-01
    • 2017-02-05
    • 2019-10-18
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    • 1970-01-01
    • 2014-11-23
    相关资源
    最近更新 更多