简体   繁体   中英

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)

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)))

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM