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

Neo*_*ang 3 erlang erlang-shell

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

perms([]) -> [[]];
perms(L) -> [[H|T] || H <- L, T <- perms(L--[H])].
* 1: syntax error before: '->'
Run Code Online (Sandbox Code Playgroud)

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

2> Perms = fun([]) -> [[]];(L) -> [[H|T] || H <- L, T <- Perms(L--[H])] end.
* 1: variable 'Perms' is unbound
Run Code Online (Sandbox Code Playgroud)

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

Hyn*_*dil 5

由于OTP 17.0有名为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.
Run Code Online (Sandbox Code Playgroud)
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]]
Run Code Online (Sandbox Code Playgroud)

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

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]]
Run Code Online (Sandbox Code Playgroud)