Question

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.

Was it helpful?

Solution

What you're looking for is called apply.

OTHER TIPS

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

(define foo2

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

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

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))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top