Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The above examples can thus be written in terms of foldr, by simply supplying the appropriate accumulator generating function and the accumulator base value:

Code Block
(define (sum lon)
    (foldr + 0 lon))

(define (get_largest_pos lon)
   (foldr (lambda (x rr)
              (if (> x rr) x rr))
          0
          lon))  

 "Forward Accumulation"

A general mantra that we have about moving data during an algorithm's execution is to say that we are "moving data from where it is, to where it can be processed".   

...

All the "outer" function, "sum_fwd", does is to set up the initial value of the accumulator.  It is is not a recursive function.   Only the helper is recursive.

We can write a template for forward accumulation, once again based on the template for a list-of-any:

Code Block

(define (f_fwd loa)
    (cond
        [(empty? loa) base]
        [(cons? loa)
            (local
                 [(define (helper acc loa)
                      (cond
                          [(empty? loa) acc]
                          [(cons? loa) (helper (... (first loa)...acc...) (rest loa))]))]
                 (helper (...first...) (rest loa)))]))