在 erlang 模块中使用匿名函数时出现问题 [英] trouble when using anonymous functions inside erlang modules

查看:34
本文介绍了在 erlang 模块中使用匿名函数时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当一个问题引起我的注意时,我正在 erlang 中使用匿名函数.函数定义如下

i was working with anonymous functionss in erlang when a problem caught my attention. the function is defined as follows

-module(qt). 
-export([ra/0]). 
ra = fun() -> 4 end. 

然而这不起作用

-export(Ra/0]). 
Ra = fun() -> 4 end. 

这也没有谁能告诉我为什么 erlang 表现出这种行为?

and neither does this can anyone tell me why erlang exhibits this behaviour ?

推荐答案

Erlang 模块不能导出变量,只能导出函数.

An Erlang module cannot export variables, only functions.

您可以通过导出一个只返回一个值的零参数函数(匿名函数是一个有效的返回值)来实现类似于导出变量的效果:

You can achieve something similar to exporting variables by exporting a function with zero arguments that simply returns a value (an anonymous function is a valid return value):

-module(qt).
-export([ra/0]).
ra() ->
    fun() -> 4 end.

现在您可以在 shell 中使用它了:

Now you can use it from the shell:

1> c(qt).
{ok,qt}
2> qt:ra().
#Fun<qt.0.111535607>
3> (qt:ra())().
4

这篇关于在 erlang 模块中使用匿名函数时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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