方案 - 列表的递归函数

发布于 2024-11-02 14:09:59 字数 580 浏览 0 评论 0原文

我有这个程序:

(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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

尐偏执 2024-11-09 14:09:59

记住 map 的作用 - 它将函数应用于列表的每个元素。因此,在第一次调用时,此函数:

(lambda (sub-tree)
           (if (list? sub-tree)
               (scale-tree sub-tree factor)
               (* sub-tree factor)))

应用于列表的元素: 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:

(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). And so on in the recursive calls.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文