在Erlang中,你如何动态调用函数? [英] In Erlang, how do you invoke a function dynamically?

查看:463
本文介绍了在Erlang中,你如何动态调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用要调用的函数的名称来调用xyz。

I want to call xyz with the name of a function to be invoked.

-module(sample).
-export([xyz/1]).

xyz(Name) -> Name().

p() -> "you called p".
g() -> "you called g".

但是我收到以下错误:

1> c(sample.erl).
./sample.erl:6: Warning: function p/0 is unused
./sample.erl:7: Warning: function g/0 is unused
{ok,sample}
2> sample:xyz('p').
** exception error: bad function p
     in function  sample:xyz/1
3>


推荐答案

正确的是,您必须导出p和g 。您可以使用apply / 3来调用它。

It is correct that you have to export p and g. You can then use apply/3 to call it.

erlang:apply(sample, p, [])

只有乐趣值可用于Fun(...)语法。你正在传递一个原子值。原子是错误消息的坏功能。你可以做类似于

Only fun-values are usable with the Fun(...) syntax. You are passing in an atom-value. An atom is a 'bad function' as the error message go. You could do something similar to

xyz(p) -> fun p/0;
xyz(g) -> fun g/0.

然后继续调用

Fun = xyz(p),
Fun()

这篇关于在Erlang中,你如何动态调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆