在方案中定义地图以接受许多列表 [英] defining map in scheme to take many lists
问题描述
我正在为方案中的方案创建一个评估程序,而我希望它具有的功能之一就是地图.但是,我发现的map的所有定义都不允许有多个列表. 例如:
I am creating an evaluator for scheme in scheme, and one of the features I want it to have is map. However, all the definitions for map I've found do not allow for multiple lists. For example:
(define (my-map proc lis)
(cond ((null? lis)
'())
((pair? lis)
(cons (proc (car lis))
(my-map proc (cdr lis))))))
此映射的定义是不完整的",因为例如您不能像这样添加2个数字列表(它只允许一个列表作为参数):
This definition of map is 'incomplete' because, for example, you cannot add 2 lists of numbers with it like so (it only allows one list as an argument):
(my-map + '(1 2 3) '(4 5 6))
如何修改上面的地图定义以允许任意数量的列表?
How do I modify the above map definition to allow an arbitrary number of lists?
推荐答案
您可以定义一个multi-map
过程,该过程可以处理多个列表,而one-map
过程仅适用于一个列表(这就是您的
You can define a multi-map
procedure that works with multiple lists in terms of a one-map
procedure that works for just one list (that's what your my-map
procedure is doing, although the second condition is a bit unusual).
假设所有列表具有相同的长度,并且至少 个列表作为参数传递给multi-map
:
Here's how, assuming that all the lists have the same length and that at least one list is passed as parameter to multi-map
:
(define (one-map proc lst)
(if (null? lst)
'()
(cons (proc (car lst))
(one-map proc (cdr lst)))))
(define (multi-map proc . lst)
(if (null? (car lst))
'()
(cons (apply proc (one-map car lst))
(apply multi-map proc (one-map cdr lst)))))
例如:
(multi-map + '(1 2 3) '(4 5 6) '(7 8 9))
=> '(12 15 18)
这篇关于在方案中定义地图以接受许多列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!