How does a loop simulation works?

[亡魂溺海] 提交于 2019-12-11 07:13:39

问题


-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 _ = a and T = [b,c]
  • call len([b,c])
    • does [b,c] match []? no
    • does [b,c] match [_|T]? yes, yielding _ = b and T = [c]
    • call len([c])
      • does [c] match []? no
      • does [c] match [_|T]? yes, yielding _ = c and T = []
      • call len([])
        • does [] match []? yes
        • len([]) returns 0
      • len([c]) returns 1 + 0
    • len([b,c]) returns 1 + 1
  • 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!