trouble when using anonymous functions inside erla

2019-05-27 01:42发布

问题:

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