gpt4 book ai didi

elixir - 使用保护子句自省(introspection)函数

转载 作者:行者123 更新时间:2023-12-02 17:08:37 25 4
gpt4 key购买 nike

给定一个模块有两个具有相同元数但不同保护子句的函数,我如何(理想情况下)查看这些子句是什么,或者至少有两个函数?

defmodule Test do
def greet(name) when name == "foo" do
IO.puts("Hello, bar")
end

def greet(name), do: IO.puts("Hello, #{name}")
end

Test.__info__(:functions) 不起作用,因为它只返回 [greet: 1]

最佳答案

您可以将模块的代码反编译为“抽象代码”并深入研究以获得此信息。以下是获取模块中每个函数的子句的方法:

module = Test

{:ok, {^module, [abstract_code: {:raw_abstract_v1, abstract_code}]}} = :beam_lib.chunks(module, [:abstract_code])

for {:function, _, name, arity, clauses} <- abstract_code do
# Uncomment the next line to print the AST of the clauses.
# IO.inspect(clauses)
IO.inspect {name, arity, length(clauses)}
end

输出:

{:__info__, 1, 7}
{:greet, 1, 2}

注意:这可能是私有(private) API,可能会在 Erlang/OTP 的 future 版本中发生变化。上面的输出是在 Erlang/OTP 20 上。

关于elixir - 使用保护子句自省(introspection)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50477425/

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