循环模拟如何工作? [英] How does a loop simulation works?
本文介绍了循环模拟如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
-module(prac).
-export([len/1]).
len([]) ->
0;
len([_|T]) ->
1 + len(T).
所以我有这个代码,它的工作原理,但我不知道如何正确地模拟它。 p>
So I have this code and it works, but I dont know how to simulate it properly.
推荐答案
如果您正在寻找一个解释为什么代码的工作原理,那么这样做。给出以下代码:
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).
如果要调用 len / 1
像 len([a,b,c])
,那么你可以想像它执行如下:
If you were to call len/1
like len([a,b,c])
, then you can think of it executing like:
- 调用
len([a,b,c])
-
,b,c]
match[]
?没有 -
[a,b,c]
match[_ | T]
?是的,产生_ = a
和T = [b,c]
- 调用
len([b,c])
-
,c]
match[]
? $[b,c] ?是的,产生
_ = b
和T = [c]
-
len([c])
-
[c]
match[]
?没有 - 确实
[c]
匹配[_ | T]
?是的,产生_ = c
和T = []
- code> len([])
-
[]
匹配[]
?是 -
len([])
返回0
- call
len([a,b,c])
- does
[a,b,c]
match[]
? no - does
[a,b,c]
match[_|T]
? yes, yielding_ = a
andT = [b,c]
- call
len([b,c])
- does
[b,c]
match[]
? no - does
[b,c]
match[_|T]
? yes, yielding_ = b
andT = [c]
- call
len([c])
- does
[c]
match[]
? no - does
[c]
match[_|T]
? yes, yielding_ = c
andT = []
- call
len([])
- does
[]
match[]
? yes len([])
returns 0
这有道理吗?
这篇关于循环模拟如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- does
- does
- does
-
-
-
查看全文