Scheme中可变参数函数的实现

Nir*_*Nir 4 scheme variadic-functions racket map-function

正如您在下面的示例中所看到的,Scheme中的map函数是可变参数函数.

> (map (lambda (number1 number2)
     (+ number1 number2))
   '(1 2 3 4)
   '(10 100 1000 10000))
'(11 102 1003 10004)
Run Code Online (Sandbox Code Playgroud)

我想实现这个可变参数选项,但我只是成功找到了两个参数map实现:

(define (map f lst)
   (if (null? lst)
       '()
       (cons (f (car lst)) (map f (cdr lst)))))
Run Code Online (Sandbox Code Playgroud)

有人可以帮我实现可变参数映射功能吗?

Jos*_*lor 9

在Scheme中,你可以编写一个可变参数函数(lambda x ...),在这种情况下x绑定到整个参数列表,或者使用一个不正确的lambda列表,例如(lambda (a b c . ds) ...),它至少需要三个参数,并绑定ds到其余参数的列表.那么你要编写的代码就像(我在R5RS Scheme中编写):

(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))))))
Run Code Online (Sandbox Code Playgroud)

这按预期工作:

(my-map + '(0 2 5) '(1 2 3))
;=> (1 4 8)
Run Code Online (Sandbox Code Playgroud)

请注意,为了使这项工作,我们需要一个非变量map(这里称为map1),以便(map1 car lists)获取要调用的参数列表function,并(map1 cdr lists)获取列表的休止符来递归.要编写可变参数map(此处称为my-map),您需要实现非可变参数map.