2016-09-24 59 views
0

現在,我一直在嘗試實施累積功能幾個星期。我已經正確地實現了一個「Map」函數,它遍歷一個列表並在每個元素上運行一個函數。在計劃中實施「收集」功能

我使用這個功能來實現「收集」

(define accumulate 
    (lambda (op base func ls) 
    (if(null? ls) 
     ls 
    (cond (not (null? (cdr ls)) (op base (map func ls) (accumulate op base func (cdr ls)))) 
     (op base (map func ls) (op base (func(car ls)))) 
    ) 
    ))) 
    ;It gets to a point (the last element) after applying the map function to each element, 
    ;where it is '(number) instead of an expected "number" (outside of()). I cannot figure out 
    ;how to circumvent this. 

我卡在如何得到這個權利。什麼是正確的方法來做到這一點?

預期的結果是:

; accumulate: combines using OP the values of a list LS after mapping a function FUNC on it 
; (accumulate + 0 sqr '(1 2 3)) => 14 
; (accumulate * 1 sqr '(1 2 3)) => 36 
; 
+0

我認爲你的'cond'語句不正確。 '(cond((not(null?(cdr ls)))(op base ...' – chepner

+0

'accumulate'的輸出應該是什麼?請提供一個帶有預期輸出的示例輸入 –

+0

另外,爲什麼你需要'map'嗎?你確定你的輸入是_lists_的列表嗎? –

回答

1

你想要實現的一個列表工作的摺疊過程中,您不需要使用map,簡單地處理依次在每個元素。這是更喜歡它:

(define accumulate 
    (lambda (op base func ls) 
    (if (null? ls) 
     base 
     (op (func (car ls)) 
      (accumulate op base func (cdr ls)))))) 

例如:

(accumulate + 0 sqr '(1 2 3)) 
=> 14 

(accumulate * 1 sqr '(1 2 3)) 
=> 36 
+0

謝謝你的建議。增加了一個預期輸出的副本供參考。 –

+0

@ChristopherKelly現在,這是不同的!看?你不需要'地圖「! –

0

可以實現你accumulatemap,爲了好玩,沒有利潤:

(define accumulate 
    (lambda (op base func ls) 
    (let ((z (map list ls))) ; box'em 
     (car (reverse   ; last 
     (map (lambda (x y) 
       (let ((acc (op (car x) (func (car y))))) 
       (set-car! y acc) 
       acc)) 
      (reverse (cdr (reverse  ; bulast 
          (cons (list base) z)))) 
      z)))))) 

(display (accumulate + 0 (lambda(x)(* x x)) (list 1 2 3 4))) 

; 0 1 2 3 
; 1 2 3 4 => 30 

這模擬(帶明顯的扭曲),在r5rs Scheme中,舊式的懶流編程定義

accumulate op base ls = last z 
         where 
          z = base : zipWith op z ls -- (:) is cons 

~> accumulate (+) 0 (map (^2) [1..4]) 
30 

-- 0 a b c d + 
-- 1 4 9 16 = 
-- 0 a b c d 

它也在過去的當前列表節點上「寫入」累積結果,因爲它沿着列表移動。這在實際中被稱爲scanl。哈斯克爾,並從該列表中取出最後一個結果使其成爲foldl(左邊的摺疊)。