User9193
User9193

Reputation: 57

How to apply each item of the list as the corresponding argument for a function in Scheme

I have a list (1 2 3) that I need to apply to the function (f a b c).

The first part of the problem was merging two lists to create the list above, now I need to plug in those numbers as arguments. I am not sure how to do this. I was thinking about using apply or map, but I am not confident in how those work or if they would be the right method.

Thank you.

Upvotes: 0

Views: 53

Answers (1)

Sylwester
Sylwester

Reputation: 48765

You are looking for the procedure apply:

(+ 1 2 3) ; ==> 6

(let ((lst '(1 2 3)))
  (apply + lst)) ; ==> 6

Apply can also take additional arguments before the list.. eg.

(let ((lst '(1 2 3)))
  (apply + 2 lst)) ; ==> 8, same as (+ 2 1 2 3)

Also know that + in Scheme is just a variable. It could have been bound in your let as well:

(let ((lst '(1 2 3))
      (+ (lambda args (apply * args))))
  (apply + 2 lst)) ; ==> 12, same as (* 2 1 2 3)

So imagine you want to do multiple operations on the same set of data.. eg. what is the result of applying x,y,an z to this list:

(let ((lst '(4 3 2))
      (procs (list + - * /)))
  (map (lambda (proc)
         (apply proc lst))
       procs))

; ==> (9 -1 24 2/3), same as (list (apply + lst) (apply - lst) ...)

Upvotes: 1

Related Questions