是否可以在Erlang shell中定义递归函数?

时间:2015-08-26 02:58:12

标签: erlang erlang-shell

我正在阅读编程Erlang,当我将它们输入到erlang REPL:




  perms([]) - > [[]];
烫发(L) - > [[H | T] || H< -L,T<  -  perms(L  -  [H])]。
 * 1:语法错误:' - >'
  
& #xA;


我知道我无法在shell中以这种方式定义函数,因此我将其更改为:




  2> Perms = fun([]) - > [[]];(L) - > [[H | T] || H< -L,T<  -  Perms(L  -  [H])] end。
 * 1:变量'Perms'未绑定
  

 


这是否意味着我无法在shell中定义递归函数?




1 个答案:

答案 0 :(得分:5)

由于OTP 17.0有名为funs:

  
      
  • Funs现在可以命名为
  •   

README中的更多详细信息:

OTP-11537  Funs can now be a given a name. Thanks to to Richard O'Keefe
           for the idea (EEP37) and to Anthony Ramine for the
           implementation.
1> Perms = fun F([]) -> [[]];
               F(L) -> [[H|T] || H <- L, T <- F(L--[H])]
           end.    
#Fun<erl_eval.30.54118792>
2> Perms([a,b,c]).
[[a,b,c],[a,c,b],[b,a,c],[b,c,a],[c,a,b],[c,b,a]]

在旧版本中,你必须更聪明一点,但是一旦你得到它:

1> Perms = fun(List) ->
               G = fun(_, []) -> [[]];
                      (F, L) -> [[H|T] || H <- L, T <- F(F, L--[H])]
                   end,
               G(G, List)
           end.    
#Fun<erl_eval.30.54118792>
2> Perms([a,b,c]).
[[a,b,c],[a,c,b],[b,a,c],[b,c,a],[c,a,b],[c,b,a]]
相关问题