Erlang 编译期间的 Eval 表达式

Eval expression during compilation time in Erlang

是否可以在 Erlang 中使用某种 constexpr 等价物?

我有点表情

obj() -> func("some string")

其中 func 是一个纯函数(结果不依赖于参数以外的任何东西),我希望它在编译期间执行。我怎样才能实现它?

编辑我可以接受任何合理的黑客攻击,只要它们允许 func 成为一个随意的函数

Erlang 有叫做 macros 的东西,它们在编译时被扩展。以下是您可以执行的操作的示例:

a.erl:

-module(a).
-compile(export_all).

-define(FUNC(Str), "hello "++Str).

go() ->
    ?FUNC("world").

在shell中:

4> compile:file("a.erl", ['P']).

{ok,[]}

^C^C

在命令行:

~/erlang_programs$ cat a.p
-file("a.erl", 1).

-module(a).

-compile(export_all).

go() ->
    "hello " ++ "world".

您可以使用 ct_expand, part of Ulf Wiger's parse_trans 存储库。要使用它,请指定编译器应使用 ct_expand 作为解析转换:

-compile({parse_transform, ct_expand}).

然后,对于要在编译时计算的每个表达式,将其包装在 ct_expand:term/1:

obj() -> ct_expand:term(func("some string")).

另见 the example module