value in a recursive loop

2019-06-01 09:41发布

问题:

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 ?

回答1:

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.


回答2:

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



标签: erlang