Erlang的开始:将功能从电子脚本转移到OTP

时间:2019-01-21 12:44:35

标签: erlang otp

在'escript'in the Erlang docs中有阶乘函数的简单实现。阶乘函数为:

fac(0) -> 1;
fac(N) -> N * fac(N-1).

没关系,我可以解决这个问题,

但是我想知道如何使用rebar3以“ OTP方式”实现相同的简单析因函数吗?

请明确,我的问题是:

  • 代码在哪里?
  • 如何从外壳中调用它?
  • 我是否也可以像通过escript示例一样从命令行运行它?

仅供参考,我从rebar3开始。这是我的位置:

rebar3 new app factorial

创建一些文件,但是具体来说,代码位于src目录中的3个文件中。我可以看到正在使用主管,看起来很好。

我可以从外壳与该项目进行交互:

$ rebar3 shell

1> application:which_applications().
[{factorial,"An OTP application","0.1.0"},
 {inets,"INETS  CXC 138 49","7.0.3"},
 {ssl,"Erlang/OTP SSL application","9.1.1"},
 {public_key,"Public key infrastructure","1.6.4"},
 {asn1,"The Erlang ASN1 compiler version 5.0.8","5.0.8"},
 {crypto,"CRYPTO","4.4"},
 {stdlib,"ERTS  CXC 138 10","3.7"},
 {kernel,"ERTS  CXC 138 10","6.2"}]
2> application:stop(factorial).
=INFO REPORT==== 21-Jan-2019::12:42:07.484244 ===
    application: factorial
    exited: stopped
    type: temporary
ok
3> application:start(factorial).
ok

1 个答案:

答案 0 :(得分:-1)

代码在哪里?

要“以OTP方式调用代码”,可以将其放在gen_server后面。

对于这个简单的阶乘函数,我在factorial.erl目录中添加了一个新文件src,这是一个标准的gen_server骨架,我的阶乘函数作为回调之一: / p>

% factorial.erl
-module(factorial).
-behaviour(gen_server).
-export([start_link/0, stop/0, calc/1]).

<skelelton gen_server stuff here, like init, etc.>

calc(N) ->
  {ok, Result} = gen_server:call(?SERVER, {calc, N}),
  {ok, Result}.

handle_call({calc, N}, _From, State) ->
  Factorial = factorial(N),
  Reply = {ok, Factorial},
  {reply, Reply, State};

factorial(0) ->
  1;
factorial(N) ->
  N * factorial(N-1).

由于我的rebar3 new app factorial创建了主管,所以我修改了主管的init,以便它调用我的factorial模块:

% factorial_sup.erl

<skeleton supervisor stuff here>

init([]) ->
  Server = {factorial, {factorial, start_link, []},
            permanent, 2000, worker, [factorial]},
  Children = [Server],
  RestartStrategy = {one_for_one, 0, 1},
  {ok, {RestartStrategy, Children}}.

如何从外壳中调用它?

$ rebar3 shell
<Enter>
1> factorial:calc(5).
{ok,120}

由于它是在主管下运行的,因此我们仍然可以停止并重新启动它:

2> application:stop(factorial).
=INFO REPORT==== 22-Jan-2019::13:31:29.243520 ===
    application: factorial
    exited: stopped
    type: temporary
ok
3> factorial:calc(5).          
** exception exit: {noproc,{gen_server,call,[factorial,{calc,5}]}}
     in function  gen_server:call/2 (gen_server.erl, line 215)
     in call from factorial:calc/1 (/Users/robert/git/factorial/src/factorial.erl, line 32)
4> application:start(factorial).
ok
5> factorial:calc(5).           
{ok,120}

如何创建可执行文件?

进行中的:-)