X10D
X10D

Reputation: 620

How to apply a function to each sublist in scheme or racket?

How to get the product of each sublist? Tried:

(apply map * '((1 2) (3 4)))

but it returns: '(3 8) while it should return '(2 12)

Upvotes: 1

Views: 383

Answers (2)

rnso
rnso

Reputation: 24545

A loop can be written with "named let":

(define (f l)
  (let loop ((l l)
             (ol '()))
    (cond
      [(empty? l) (reverse ol)]
      [else (loop (rest l)
                  (cons (apply * (first l)) ol))])))

(f '((1 2) (3 4)))

Output:

'(2 12)

Upvotes: 1

Mulan
Mulan

Reputation: 135227

You can use pattern matching

(map (λ (xs) (match xs [(list a b) (* a b)]))
     '((1 2) (3 4)))

... Or you can use map with a lambda that applies * to the sublists

(map (λ (xs) (apply * xs))
     '((1 2) (3 4)))

... Or you can use curry to replace the lambda

(map (curry apply *) '((1 2) (3 4)))

Upvotes: 6

Related Questions