简体   繁体   English

如何在方案中使用文件夹?

[英]How to use foldr in scheme?

When you use foldr, the procedure you use has 2 arguments, the current value of the list and the accumulator. 使用foldr时,所使用的过程有2个参数,即列表的当前值和累加器。 Let's say the list you iterate over is a list of list of numbers, all the same length. 假设您要遍历的列表是长度相同的数字列表。 Then as you iterate through them, you want to multiply the numbers of the same index and store it as the accumulator. 然后,当您遍历它们时,您想要乘以相同索引的数字并将其存储为累加器。

If you use lambda (x acc) (map * x acc) inside the foldr , this fails because acc I believe is an empty list in the beginning. 如果在文件foldr内使用lambda (x acc) (map * x acc) ,则此操作将失败,因为我认为acc开头是一个空列表。 How can you handle the base case like this? 您如何处理这种基本情况?

This can be solved using foldr all right, the trick is to correctly initialize the accumulated value at the beginning. 可以使用foldr解决此问题,诀窍是在开始时正确初始化累积值。 No need to do fancy stuff (like macros) here! 无需在这里做任何花哨的东西(例如宏)!

(define lst '((1 2 3) (2 3 5) (3 5 7)))

(foldr (lambda (x acc) (map * x acc))
       (car lst)
       (cdr lst))

=> '(6 30 105)

Of course, if the list is empty (car lst) will fail. 当然,如果列表为空(car lst)将失败。 So you might want to handle the empty list as a separate case before invoking foldr . 因此,您可能需要在调用foldr之前将空列表作为一个单独的案例处理。

Say you have a list of lists as follows: 假设您有一个列表列表,如下所示:

((1 2 3) (2 3 5) (3 5 7))

You want to reduce it to: 您希望将其减少为:

(6 30 105)

I would simple do: 我会简单地做:

(define-syntax mul
    (syntax-rules ()
        ((_ (lists ...)) (map * 'lists ...))))

The you can use it as follows: 您可以按以下方式使用它:

(mul ((1 2 3) (2 3 5) (3 5 7))) ; => (6 30 105)

The above code simply expands to: 上面的代码只是扩展为:

(map * '(1 2 3) '(2 3 5) '(3 5 7))

Then you can fold the resulting list. 然后,您可以折叠结果列表。 For example: 例如:

(foldr + 0 (mul ((1 2 3) (2 3 5) (3 5 7)))) ; => 141

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM