value in a recursive loop

2019-06-01 09:50发布

In a recursive loop, I would like to change the value of a variable:

loop(N) when N > ... ->
N;
loop(N) ->
case ... of
  N+1
  ...
end,
...
case ... of
  N-1
  ...
end,
...
loop(N).

How to "pass" the new value of N ?

标签: erlang
2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-06-01 10:28

Since you can't change the value of N once assigned, you need to call loop with the new value:

loop(N) ->
    loop(N+1).

Alternatively, create a temporary variable to hold its new value before passing it into the recursive loop invocation.

loop(N) ->
    NewN = N+1,
    loop(NewN).

If this results in a lot of repetition in your code, you might want to separate the looping construct from the logic which produces the new value of N:

loop(N) ->
    NewN = logic(N),
    loop(NewN).

logic(N) ->
    N+1.
查看更多
Luminary・发光体
3楼-- · 2019-06-01 10:36

You simply call the function with a new value:

$ cat fac.erl
-module(fac).
-export([fac/1]).

fac(0) -> 1;
fac(N) when N > 0 -> N*fac(N-1).

$ erl
Erlang R13B03 (erts-5.7.4) [source] [64-bit] [smp:8:8] [rq:8] [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.7.4  (abort with ^G)
1> c(fac).
{ok,fac}
2> fac:fac(10).
3628800
3> q().
ok
4> $

Shamelessly stolen from: http://learnyousomeerlang.com/recursion#hello-recursion

查看更多
登录 后发表回答