trouble when using anonymous functions inside erlang modules

走远了吗. 提交于 2019-12-10 11:33:03

问题


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. 

this however does not work

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

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


回答1:


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.

Now you can use it from the shell:

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


来源:https://stackoverflow.com/questions/18401291/trouble-when-using-anonymous-functions-inside-erlang-modules

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!