如何将列表作为球拍中的参数列表传递?

发布于 2024-11-29 02:51:53 字数 416 浏览 0 评论 0原文

我有这样的声明:

 ((lambda (a b c) (+ a b c)) 1 2 3) ; Gives 6

我希望也能够向它传递一个列表,如下所示:

((lambda (a b c) (+ a b c)) (list 1 2 3))

...除非这不起作用,因为整个列表都作为“a”传递。有没有办法将列表分解为参数?

我正在寻找类似于Python中的*字符的东西。对于那些不熟悉语法的人:

 def sumthree(a, b, c):
   print a + b + c

 sumthree(1, 2, 3) # Prints 6
 sumthree(*(1, 2, 3)) # Also prints 6

I have a statement like this:

 ((lambda (a b c) (+ a b c)) 1 2 3) ; Gives 6

And I would like to be able to also pass it a list as so:

((lambda (a b c) (+ a b c)) (list 1 2 3))

...except this doesn't work because the entire list is passed as 'a.' Is there is a way to explode the list into arguments?

What I'm looking for is something similar to the * character in Python. For those of you unfamiliar with the syntax:

 def sumthree(a, b, c):
   print a + b + c

 sumthree(1, 2, 3) # Prints 6
 sumthree(*(1, 2, 3)) # Also prints 6

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

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

发布评论

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

评论(2

旧时浪漫 2024-12-06 02:51:53

该操作称为apply

(apply + (list 1 2 3))   ; => 6

apply “扩展”最后一个参数;任何先前的参数都按原样传递。所以这些都是一样的:

(apply + 1 2 3 (list 4 5 6))
(apply + (list 1 2 3 4 5 6))
(+ 1 2 3 4 5 6)

That operation is called apply.

(apply + (list 1 2 3))   ; => 6

apply "expands" the last argument; any previous arguments are passed as is. So these are all the same:

(apply + 1 2 3 (list 4 5 6))
(apply + (list 1 2 3 4 5 6))
(+ 1 2 3 4 5 6)
请止步禁区 2024-12-06 02:51:53

请注意以下定义

(define (a . b) (apply + b))
(a 1)
(a 1 2)
(a 1 2 3)

“.”使您能够将任意数量的参数传递给函数。您仍然可以拥有必需的参数

(define (f x . xs) (apply x xs)) ;; x is required
(f + 1 2 3) ;; x is +, xs is (1 2 3)

Pay attention to the following definition

(define (a . b) (apply + b))
(a 1)
(a 1 2)
(a 1 2 3)

'.' gives you ability to pass any number of arguments to a function. You can still have required arguments

(define (f x . xs) (apply x xs)) ;; x is required
(f + 1 2 3) ;; x is +, xs is (1 2 3)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文