apply函数用法

apply函数用法

procedure:  (apply proc arg1 ... args) 

Proc must be a procedure and args must be a list. Calls proc with the elements of the list (append (list arg1 ...args) as the actual arguments.

(define (f x y z) (+ x y z))
;等效: (f
1 2 3) (apply f '(1 2 3)) (apply f 1 '(2 3)) (apply f 1 2 '(3))
;将发生错误:
;(apply f '(1) 2 3) ;(apply f '(1 2) 3) ;(apply f 1 '(2) 3)

(list arg1 ...)部分可以省略,也可以和args合并为一个新列表.这种设置在处理不定参数的函数时非常实用.例如下面自定义imap函数模拟map的运作:

(define (imap f x . y)
  (if (null? y) 
      (let im ((x x)) 
        (if (null? x) 
            '() 
            (cons (f (car x)) (im (cdr x))))) 
      (let im ((x x) (y y)) 
        (if (null? x) 
            '() 
            (cons (apply f (car x) (imap car y)) (im (cdr x) (imap cdr y)))))))
(apply f (car x) (imap car y))即为体现.