在方案中列出作为参数

发布于 2024-09-04 12:33:59 字数 380 浏览 2 评论 0原文

假设我有一个过程 foo,它接受三个参数,并返回一个列表,其中所有参数都加倍:

(define  (foo a b c)
  (list (* 2 a ) (* 2 b) (* 2 c)))

我想要做的是创建另一个接受列表的过程,并使用列表元素作为参数调用 foo,像这样:

(define (fooInterface myList)
  ...)

(fooInterface (list 1 2 3))

问题是,我不想编写 fooInterface 假设 foo 总是有 3 个参数。也就是说,如果我向 foo 添加额外的参数,则 fooInterface 应该仍然可以工作,只要传入的列表有 3 个元素。

Let's say I have a procedure foo that takes three arguments, and returns a list of them all doubled:

(define  (foo a b c)
  (list (* 2 a ) (* 2 b) (* 2 c)))

What I'd like to be able to do is create another procedure which accepts a list, and calls foo using the list elements as arguments, like this:

(define (fooInterface myList)
  ...)

(fooInterface (list 1 2 3))

The catch is, I don't want to write fooInterface assuming foo will always have 3 arguments. That is, if I add an extra argument to foo, fooInterface should still work provided the list passed in has 3 elements.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

〗斷ホ乔殘χμё〖 2024-09-11 12:33:59

您要查找的内容称为 apply

What you're looking for is called apply.

柠檬心 2024-09-11 12:33:59

map 怎么样,它可以与不同的过程定义一起使用吗?

(define foo2

(lambda (x)
  (* x 2)))

(map foo2 '(1 2 3 4 5))

How about map , would that work with a different procedure definition?

(define foo2

(lambda (x)
  (* x 2)))

(map foo2 '(1 2 3 4 5))
醉城メ夜风 2024-09-11 12:33:59

一些实现可以做你想做的事...

(define (foo lst)
  (map (lambda (x) (* 2 x)) lst))

(define (foo lst)
  (apply (lambda args (map (lambda (x) (* x 2)) args)) lst))

(define foo
  (lambda args (map (lambda (x) (* x 2)) args))

只是为了好玩,apply 的一个非常酷的用途是转置矩阵。考虑一下:

(define grid     '((1 2 3) 
                   (4 5 6) 
                   (7 8 9)
))

那么,

(apply map list grid)
=> '((1 4 7)
     (2 5 8)
     (3 6 9))

Some implementations to do what you want...

(define (foo lst)
  (map (lambda (x) (* 2 x)) lst))

(define (foo lst)
  (apply (lambda args (map (lambda (x) (* x 2)) args)) lst))

(define foo
  (lambda args (map (lambda (x) (* x 2)) args))

Just for fun, a really cool use of apply is in transposing a matrix. Consider:

(define grid     '((1 2 3) 
                   (4 5 6) 
                   (7 8 9)
))

Then,

(apply map list grid)
=> '((1 4 7)
     (2 5 8)
     (3 6 9))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文