【问题标题】:spawn function in erlang using function in another module使用另一个模块中的函数在erlang中生成函数
【发布时间】:2013-07-22 06:46:24
【问题描述】:

过去一周我一直在学习 erlang,并且正在阅读 Joe Armstrong 的 Pragmatic erlang 书。我正在编写一些代码来生成进程并且遇到了一种情况 我在模块 myatom.erl 中有一个函数,看起来像这样

 start(anatom,Fun) ->
       case whereis(anatom) of
               undefined -> 
                       Pid = spawn(Fun),
                       try register(anatom,Pid) of
                               true -> true
                      catch
                       error:Reason ->
                              Reason
                      end;
              Other -> {error,already_defined}
      end. 

在另一个名为 tloop.erl 的模块中有一个函数

loop() ->
   receive 
        { From , No } -> From ! { self(), No*4};
        Other -> void
   end. 

如果我要使用 start() 在 erlang shell 中生成循环,我该怎么做? 当我这样做时出现以下错误

anatom:start(atomname,tloop:loop). 

提前致谢!

anatom:start(myatom,fun tloop:loop). 
* 2: syntax error before: ')

【问题讨论】:

    标签: erlang


    【解决方案1】:

    你必须写以下内容

    anatom:start(myatom, fun tloop:loop/0).
    

    您必须指定函数的arity(参数数量),因为在erlang中具有相同名称但不同arity的函数不被认为是同一个函数。

    【讨论】:

    • 感谢您的回答。然而这也行不通,我相信真正的原因是当我们用新原子调用函数时说 newatom ,erlang 无法匹配 start 主体中的任何模式 (newatom , fun)。它期望所有调用都匹配(myatom,fun)。所以我用 AnAtom 替换了体内的 myatom,它可以工作了
    • 当然,函数参数必须匹配:)
    猜你喜欢
    • 2021-04-19
    • 1970-01-01
    • 2018-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    • 1970-01-01
    • 2019-05-02
    相关资源
    最近更新 更多