你如何写一个在 Erlang 中递归的乐趣? [英] How do you write a fun that's recursive in Erlang?

查看:17
本文介绍了你如何写一个在 Erlang 中递归的乐趣?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Erlang shell 中编写递归乐趣,但我不断收到未绑定的变量异常:

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.

推荐答案

自从 OTP 17.0有命名的乐趣:

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]]

在此之前,您可以使用一个小参数技巧来做到这一点:

Before that you could do this 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.

一次拍摄的替代方法:

1> Foo = fun(X) -> Fun = fun(F,Y) -> F(F,Y) end, Fun(Fun,X) end.
#Fun<erl_eval.6.13229925>
2> Foo(a).

例如:

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]

这篇关于你如何写一个在 Erlang 中递归的乐趣?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆