2

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.

YasirA
  • 9,531
  • 2
  • 40
  • 61
Cam
  • 14,930
  • 16
  • 77
  • 128
  • `(map (lambda (x) (* 2 x)) thatList)`? – kennytm Jun 01 '10 at 19:08
  • @KennyTM: Yes, that would provide the same final output for this example. However the functionality I was trying to get at here was using list elements as arguments for a procedure (see Eli's answer). – Cam Jun 01 '10 at 19:11

3 Answers3

11

What you're looking for is called apply.

Archy Will He 何魏奇
  • 9,589
  • 4
  • 34
  • 50
Eli Barzilay
  • 29,301
  • 3
  • 67
  • 110
0

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))
snario
  • 453
  • 2
  • 6
  • 15
0

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

(define foo2

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

(map foo2 '(1 2 3 4 5))
Nilesh
  • 20,521
  • 16
  • 92
  • 148