方案 - 列表的递归函数
我有这个程序:
(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)
这段代码是如何工作的?首先,我们将整个列表作为参数 (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))
作为参数。树子树Factor) 和 (list 1 (list 2 (list 3 4) 5) (list 6 7))
再次,
谢谢。
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?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
记住
map
的作用 - 它将函数应用于列表的每个元素。因此,在第一次调用时,此函数:应用于列表的元素:
1
、(list 2 (list 3 4) 5)
和(列表 6 7)
。递归调用中依此类推。Remember what
map
does - it applies a function to every element of a list. So on the first call, this function:is being applied to the elements of your list:
1
,(list 2 (list 3 4) 5)
, and(list 6 7)
. And so on in the recursive calls.