问题
-module(prac).
-export([len/1]).
len([]) ->
0;
len([_|T]) ->
1 + len(T).
So I have this code and it works, but I dont know how to simulate it properly.
回答1:
Okay, if you're looking for an explanation of why the code works the way it does, it goes something like this. Given the following code:
len([]) -> 0;
len([_|T]) -> 1 + len(T).
If you were to call len/1 like len([a,b,c]), then you can think of it executing like:
- call
len([a,b,c]) - does
[a,b,c]match[]? no - does
[a,b,c]match[_|T]? yes, yielding_ = aandT = [b,c] - call
len([b,c])- does
[b,c]match[]? no - does
[b,c]match[_|T]? yes, yielding_ = bandT = [c] - call
len([c])- does
[c]match[]? no - does
[c]match[_|T]? yes, yielding_ = candT = [] - call
len([])- does
[]match[]? yes len([])returns 0
- does
len([c])returns 1 + 0
- does
len([b,c])returns 1 + 1
- does
len([a,b,c])returns 1 + 2
Does that make sense?
回答2:
Erlang has a debugger call im()
try to use it
来源:https://stackoverflow.com/questions/41008186/how-does-a-loop-simulation-works