How do I pass a list as a list of arguments in racket?

前端 未结 2 1374
日久生厌
日久生厌 2020-12-17 15:34

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:

相关标签:
2条回答
  • 2020-12-17 16:06

    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)
    
    0 讨论(0)
  • 2020-12-17 16:26

    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)
    
    0 讨论(0)
提交回复
热议问题