gpt4 book ai didi

macros - 如何 “splat” 动态创建函数的函数参数

转载 作者:行者123 更新时间:2023-12-02 01:01:12 26 4
gpt4 key购买 nike

我正在模块中生成一些函数:

defmodule M do
funs = [do_it: [:arg1, :arg2]]

Enum.each(funs, fn {name, args} ->
args = Enum.map(args, & {&1, [], Elixir})
def unquote(name)(unquote(args)),
do: IO.inspect(unquote(args))
end)
end

问题是生成的函数显然接受一个参数,即大小为 2 的列表:

▶ M.__info__(:functions) 
#⇒ [do_it: 1]

目标是动态声明接受两个参数的函数。在 Ruby 术语中,这将是unsplat参数列表。

是否有可能在不模式匹配 {:do_it, blah, [[ list of argument ]]} 的结果 AST 并手动展平列表的情况下完成此任务?

最佳答案

您可以使用Kernel.SpecialForms.unquote_splicing/1args 列表中的“splice”:

defmodule M do
funs = [do_it: [:arg1, :arg2], do_it: [:arg1, :arg2, :arg3]]

Enum.each(funs, fn {name, args} ->
def unquote(name)(unquote_splicing(args)), do: :ok
end)
end
iex(1)> M.__info__(:functions)
[do_it: 2, do_it: 3]

关于macros - 如何 “splat” 动态创建函数的函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47708870/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com