;; ------ foldr-right (foldr) for reverse accumulation (natural recursion) problems --- ;; sum the numbers in a list (define (sumNums aList) (cond [(empty? aList) 0] [(cons? aList) (+ (first aList) (sumNums (rest aList)))])) "sumNums test:" (sumNums (list 1 2 3 4 5)) ;; What is the invariant process? ;; abstract a little by pulling the "+" out (define (sumNums2 aList) (local [(define (func aFirst rr) ;; rr = recursive result (+ aFirst rr))] (cond [(empty? aList) 0] [(cons? aList) (func (first aList) (sumNums (rest aList)))]))) "sumNums2 test:" (sumNums2 (list 1 2 3 4 5)) ;; abstract a little by more by pulling ;; func out of the function completely ;; pull the zero base case value out too ;; rename sumNums2 to foldright as it is now 100% invariant code (define (func aFirst rr) ;; rr = recursive result (+ aFirst rr)) (define (foldright func base aList) (cond [(empty? aList) base] [(cons? aList) (func (first aList) (foldright func base (rest aList)))])) "foldright test:" (foldright func 0 (list 1 2 3 4 5)) "or" (foldright (lambda (aFirst rr) (+ aFirst rr)) 0 (list 1 2 3 4 5)) "or" (foldright + 0 (list 1 2 3 4 5)) ;; ---- fold-left (foldl)for forward accumulation problems ------- ;;reverse a list (define (reverseList myList) (local [(define (helper acc aList) (cond [(empty? aList) acc] [(cons? aList) (helper (cons (first aList) acc) (rest aList))]))] (helper empty myList))) "reverseList test:" (reverseList (list 1 2 3 4 5)) ;; What are the invariant processes? ;; abstract a little bit by puting the cons into a function (define (reverseList2 myList) (local [(define (helper acc aList) (local [(define (func aFirst acc) (cons aFirst acc))] (cond [(empty? aList) acc] [(cons? aList) (helper (func (first aList) acc) (rest aList))])))] (helper empty myList))) "reverseList2 test:" (reverseList2 (list 1 2 3 4 5)) ;; abstract a little bit more ;; by pulling the function out of the helper (define (reverseList3 myList) (local [(define (func aFirst acc) (cons aFirst acc)) (define (helper func acc aList) (cond [(empty? aList) acc] [(cons? aList) (helper func (func (first aList) acc) (rest aList))]))] (helper func empty myList))) "reverseList3 test:" (reverseList3 (list 1 2 3 4 5)) ;; helper doesn't depend on reversing anymore. ;; helper is 100% invariant code, so pull it out completely ;; rename it "foldleft" (define (foldleft func acc aList) (cond [(empty? aList) acc] [(cons? aList) (foldleft func (func (first aList) acc) (rest aList))])) ;; reverse is now just (using a lambda instead of a defined function) (define (reverseList4 myList) (foldleft (lambda (aFirst acc) (cons aFirst acc)) empty myList)) "reverseList4 test:" (reverseList4 (list 1 2 3 4 5))