Jesper F.
Jesper F.

Reputation: 89

Scheme: Mapping a list as argument to a function

If I have a function that takes 3 arguments, and returns a list:

(some-function 1 2 3) --> '(3 2 1)

and I have a list of lists like this:

( (1 2 3) (2 1 3) (3 2 1) )

How can I map "some-function" to use all the lists as elements?

Thank you.

Upvotes: 0

Views: 457

Answers (2)

Svante
Svante

Reputation: 51541

I am not sure what result you mean.

(define (rev-list a b c)
  (list c b a))

(rev-list 1 2 3)
⇒ (3 2 1)

(apply rev-list '((1 2 3) (2 1 3) (3 2 1)))
⇒ ((3 2 1) (2 1 3) (1 2 3))

(map (lambda (l) (apply rev-list l)) '((1 2 3) (2 1 3) (3 2 1)))
⇒ ((3 2 1) (3 1 2) (1 2 3))

Upvotes: 2

julius383
julius383

Reputation: 101

If the lists are only nested once then it is possible to turn them into a single list using fold and append and call some-function on the result with apply i.e

(fold append '() '((1 2 3) (2 1 3) (3 2 1))) => (2 3 1 3 2 1 1 2 3)
(apply some-function (2 3 1 3 2 1 1 2 3))

Otherwise you can just wrap apply and the some-function in a lambda you pass to map

(map (lambda (x) (apply some-function x)) '((1 2 3) (2 1 3) (3 2 1)))

Upvotes: 2

Related Questions