你如何写一个在Erlang中递归的乐趣? [英] How do you write a fun that's recursive in Erlang?
本文介绍了你如何写一个在Erlang中递归的乐趣?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在Erlang shell中编写一个递归的乐趣,但是我仍然收到一个未绑定的变量异常: 1 GT; Foo = fun(X) - > Foo(X)结束。
* 1:变量'Foo'未绑定
这可能不用说,但是'不是想创造一个无限循环!
解决方案
你可以通过一个小的参数来实现: / p>
1> Foo = fun(F,X)→> F(F,X)结束。
#Fun< erl_eval.12.113037538>
2> Foo(Foo,a)。
< ...无限循环!>
这里的技巧是将函数作为参数发送给自身以允许递归。 >
在一次拍摄中使用的另一种方式:
1> Foo = fun(X) - >乐趣=乐趣(F,Y) - > F(F,Y)结束,Fun(Fun,X)结束。
#Fun< erl_eval.6.13229925>
2>美孚(一)。
例如:
1> Foo = fun(Max) - >
1>乐趣=乐趣(F,X)当X>最大 - > [];
1> (F,X)→> [X | F(F,X + 1)]
1>结束,
1> Fun(Fun,0)
1>结束。
#Fun< erl_eval.6.13229925>
2> FOO(10)。
[0,1,2,3,4,5,6,7,8,9,10]
由于 OTP 17.0 有命名乐趣,使任务更容易:
1> Perms = fun F([]) - > [[]]; F(L)→& [[H | T] || H <-L,T #Fun< erl_eval.30.54118792>
2>烫发([A,B,C])。
[[a,b,c],[a,c,b],[b,a,c],[b,c,a],[c,a,b],[c, a]]
I'm trying to write a recursive fun in an Erlang shell, but I keep getting an unbound variable exception:
1> Foo = fun(X) -> Foo(X) end.
* 1: variable 'Foo' is unbound
This probably goes without saying, but I'm not trying to create an infinite loop! This is just a simple example of the error I'm getting.
解决方案
You can do it with a little argument trick:
1> Foo = fun(F, X) -> F(F, X) end.
#Fun<erl_eval.12.113037538>
2> Foo(Foo, a).
<...infinite loop!>
The trick here is to send in the function as an argument to itself to allow recursion.
Alternative way to make it in one shoot:
1> Foo = fun(X) -> Fun = fun(F,Y) -> F(F,Y) end, Fun(Fun,X) end.
#Fun<erl_eval.6.13229925>
2> Foo(a).
For example:
1> Foo = fun(Max) ->
1> Fun = fun(F, X) when X > Max -> [];
1> (F, X) -> [X | F(F, X+1)]
1> end,
1> Fun(Fun, 0)
1> end.
#Fun<erl_eval.6.13229925>
2> Foo(10).
[0,1,2,3,4,5,6,7,8,9,10]
Since OTP 17.0 there are named funs which makes the task a lot easier:
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]]
这篇关于你如何写一个在Erlang中递归的乐趣?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文