Can Scheme expand a list as arguments?

ⅰ亾dé卋堺 提交于 2020-01-30 04:43:46

问题


Considered that I have a procedure (plus x y) witch takes exactly two args. And now I also have a list which contains two objects like (list 1 2). So, if there's any magic way to expand the list as two arguments. We have a dot notion version, but that isn't what i want. I just want to expand the list to make Scheme believe I passed two arguments instead of a list.

Hope those Ruby codes help:

a = [1, 2]
def plus(x,y); x+y; end

plus(*a)
# See that a is an array and the plus method requires
# exactly two arguments, so we use a star operator to
# expand the a as arguments

回答1:


(apply your-procedure your-list)



回答2:


This is Scheme's equivalent code:

(define (plus x y)
  (+ x y))

(plus 1 2)
=> 3

(define a (list 1 2))
(apply plus a)
 => 3

The "magic" way to expand the list and pass it as arguments to the procedure, is using apply. Read more about it your interpreter's documentation.



来源:https://stackoverflow.com/questions/17035725/can-scheme-expand-a-list-as-arguments

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!