天天看点

erlang 自定义函数的初步应用

一、模块内调用

1> AA=fun(BB)-> io:format("this is test args ~s~n",[BB]) end.

#Fun<erl_eval.6.17052888>

2> AA(aa).

this is test argsaa

ok

3> BB=fun()-> io:format("this is BB FUN ~n",[]) end.      

#Fun<erl_eval.20.17052888>

4> BB().

this is BB FUN

5> spawn( BB).  

<0.62.0>

6> spawn(fun()-> AA(cc) end).

this is test argscc

<0.67.0>

7> Fun =fun(A,B)-> io:format("the product is:~w~n",[A*B]) end.

#Fun<erl_eval.12.80484245>

8> Fun2 =fun(Fun,A,B) ->Fun(A,B) end.

#Fun<erl_eval.18.80484245>

9> Fun2(Fun,2,4).

the product is:8

二、跨模块调用

-module(mod_user).

-export([test/0]).

test()->

    io:format("hello test ~n").

1> mod_user:test().

hello test

2> spawn(fun mod_user:test/0).

<0.35.0>

3> spawn(mod_user,test,[]).

<0.37.0>

备注:2 只能用于空参数的函数,否则只能用3代替。

三、需要写到文件中

  test(A,B)-> io:format("the product is:~w~n",[A*B]) .

  test_fun(Fun,A,B)-> Fun(A,B).

  test_import()-> test_fun(fun test/2,2,3).

 需要导出test_import/0,然后在控制台调用module:test_import().

上一篇: 需要测试

继续阅读