Way to explode list into arguments?

拜拜、爱过 提交于 2020-01-04 16:25:32

问题


Assume I have a procedure upto that when called like (upto 1 10) will generate the list '(1 2 3 4 5 6 7 8 9 10).

If I want to use this list as arguments to a function like lcm that takes multiple arguments rather than a single list, like (lcm 1 2 3 4 5 6 7 8 9 10) is there a way to do this?


回答1:


Use apply: e.g

(apply lcm (upto 1 10))

"apply" applies a function to a list of arguments.




回答2:


One way I found to do this using eval is the following:

(eval (cons 'lcm (upto 1 10)))




回答3:


In MIT-Scheme (unsure of others) you can use the dot in your function definition.

(define (func-with-multiple-args . args)
  (let loop ((args args))
    (if (null? args)
      'done
      (begin (display (car args)) (loop (cdr args))))))

Calling with

(func-with-multiple-args 1 2 3 4)

will do the job. Note that the args get put into a list.

Fun fact: the `list' procedure is actually defined in list.scm of the MIT-Scheme "runtime" source as:

(define (list . args)
 args)


来源:https://stackoverflow.com/questions/14483797/way-to-explode-list-into-arguments

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