(lambda x ...)
在Scheme中,你可以写x
一个(lambda (a b c . ds) ...)
可变参数函数为ds
. 那么,您尝试编写的代码将类似于(我正在使用 R5RS 方案编写):
(define (my-map function list1 . more-lists)
(define (some? function list)
;; returns #f if (function x) returns #t for
;; some x in the list
(and (pair? list)
(or (function (car list))
(some? function (cdr list)))))
(define (map1 function list)
;; non-variadic map. Returns a list whose elements are
;; the result of calling function with corresponding
;; elements of list
(if (null? list)
'()
(cons (function (car list))
(map1 function (cdr list)))))
;; Variadic map implementation terminates
;; when any of the argument lists is empty
(let ((lists (cons list1 more-lists)))
(if (some? null? lists)
'()
(cons (apply function (map1 car lists))
(apply my-map function (map1 cdr lists))))))
这按预期工作:
(my-map + '(0 2 5) '(1 2 3))
;=> (1 4 8)
请注意,为了完成这项工作,我们需要一个非可变参数map
(这里称为map1
)(map1 car lists)
来获取要调用的参数列表function
,并(map1 cdr lists)
获取要递归的其余列表。要编写一个可变参数map
(这里称为my-map
),您已经需要一个非可变参数的实现map
。