2012-10-10 130 views
2

我想寫傳遞函數和一些列表的功能apply-all,併產生的函數值的列表應用,所有功能時應用到數實施球拍

例如,

(apply-all (list sqrt square cube) 4) => (2 16 64)) 

假定所有功能先前已經被定義

我知道如何分開來寫每個功能,以及如何將工作,但我有點困惑如何去這樣做一個加工什麼函數傳遞

+0

重複http://stackoverflow.com/questions/9797991/applying-a-list-of-functions-to-a-number的 –

回答

3

您需要遍歷功能列表,依次對於每個功能,它適用於數量參數。要做到這一點最簡單的方法是使用map過程:

(define (apply-all flist num) 
    (map (lambda (f) (f num)) 
     flist)) 

(apply-all (list sqrt square cube) 4) 
=> '(2 16 64) 
1

這裏有一個辦法做到這一點,我喜歡,用for/list

(define (apply-all fs n) 
    (for/list ([f fs]) 
    (f n))) 
1
(define (apply-all fs n) 
    (cond 
    ((null? fs) fs) 
    (else (cons ((car fs) n) (apply-all ??? ???))))) 

大概是你應該到什麼寫,如果這是一項任務。