[英]scheme - recursive function of lists
I have this program: 我有这个程序:
(define scale-tree
(lambda (tree factor)
(map (lambda (sub-tree)
(if (list? sub-tree)
(scale-tree sub-tree factor)
(* sub-tree factor)))
tree)))
(scale-tree (list 1 (list 2 (list 3 4) 5) (list 6 7))
10)
How does this code work? 此代码如何工作? First, we give it the whole list as parameter (list 1 (list 2 (list 3 4) 5) (list 6 7))
, and in the first call, the (lambda (sub-tree)
gets the (list 1 (list 2 (list 3 4) 5) (list 6 7))
as parameter. For that, we call (scale-tree sub-tree factor)
with (list 1 (list 2 (list 3 4) 5) (list 6 7))
again. When does the list reduce? 首先,我们将整个列表作为参数(list 1 (list 2 (list 3 4) 5) (list 6 7))
作为参数,在第一个调用中, (lambda (sub-tree)
获得(list 1 (list 2 (list 3 4) 5) (list 6 7))
作为参数,为此,我们用(list 1 (list 2 (list 3 4) 5) (list 6 7))
调用(scale-tree sub-tree factor)
(list 1 (list 2 (list 3 4) 5) (list 6 7))
。列表何时减少?
Thank you. 谢谢。
Remember what map
does - it applies a function to every element of a list. 记住map
作用-它将函数应用于列表的每个元素。 So on the first call, this function: 因此,在第一次调用时,此函数:
(lambda (sub-tree)
(if (list? sub-tree)
(scale-tree sub-tree factor)
(* sub-tree factor)))
is being applied to the elements of your list: 1
, (list 2 (list 3 4) 5)
, and (list 6 7)
. 应用于列表中的元素: 1
, (list 2 (list 3 4) 5)
和(list 6 7)
。 And so on in the recursive calls. 以此类推在递归调用中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.