Scheme中可变参数映射函数的实现 [英] Implementation of variadic map function in Scheme

查看:97
本文介绍了Scheme中可变参数映射函数的实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

As you can see in the example below, map function in Scheme is variadic function.

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

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

I want to implement this variadic option, but I only succeeded to find the two arguments map implementation:

(define (map f lst)
   (if (null? lst)
       '()
       (cons (f (car lst)) (map f (cdr lst)))))

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

Can someone help me implement variadic map function?

推荐答案

在 Scheme 中,您可以将可变参数函数编写为 (lambda x ...),在这种情况下 x 绑定到整个参数列表,或者通过使用不正确的 lambda 列表,例如 (lambda (abc . ds) ...),至少需要 em> 三个参数,并将 ds 绑定到其余参数的列表.那么,您尝试编写的代码将类似于(我正在使用 R5RS 方案编写):

In Scheme, you can write a variadic function as (lambda x ...), in which case x gets bound to the entire list of arguments, or by using an improper lambda list, e.g., (lambda (a b c . ds) ...), which takes at least three arguments, and binds ds to the list of the remaining arguments. The code you're trying to write, then, would be something like (I'm writing in 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))))))

这按预期工作:

(my-map + '(0 2 5) '(1 2 3))
;=> (1 4 8)

请注意,要完成这项工作,我们需要一个非可变参数的map(此处称为map1)来执行(map1 car lists) 获取参数列表以调用 function(map1 cdr lists) 获取列表的其余部分进行递归.要编写可变参数 map(此处称为 my-map),您已经需要非可变参数 map 的实现.

Notice that to make this work, we needed a non-variadic map (here called map1) in order to do (map1 car lists) to get the argument list to call function with, and (map1 cdr lists) to get the rests of the lists to recurse with. To write a variadic map (here called my-map), you already need an implementation of the non-variadic map.

这篇关于Scheme中可变参数映射函数的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆