Versions Compared

Key

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

...

  1. The "..."'s in both the helper and the outer cons? clause must be identical.
  2. "base" must represent a value, as opposed to something such as a exception.

For instance, the finding the largest element in a list follows only the first template:

It is important to emphasize again that this is a special case where a base value is well-defined.   The general case template above will always work and should be the template of choice if you are not sure how to write your forward accumulation algorithm.   Once you get it working, you can convert it to the more specialized case here if it warrants it.  

For instance, the finding the largest element in a list follows only the first template:

Code Block

(define (get_largest
Code Block

(define (get_largest lon)
  (cond
    [(empty? lon) (error "no largest in an empty list")]
    [(cons? lon)
     (local
       [(define (helper acc lon2)
          (cond
            [(empty? lon2) acc]
            [(cons? lon2) (helper (if (> (first lon2) acc) (first lon2) acc) (rest lon2))]))]
       (helper (first lon) (rest lon)))]))   

...

Code Block
;; foldl: (lambda any1 any2 --> any2) any2 list-of-any1 --> any2
(define (foldl func base loa)
   (cond
      [(empty? loa) base]
      [(cons? loa)
       (local
          [(define (helper acc loa2)
              (cond
                 [(empty? loa2) acc]
                 [(cons? loa2) (helper (func (first loa2) acc ) (rest loa2))]))]
          (helper base loa))]))   

...

Once again, our template has reduced down to the 100% concrete code of a higher-order function. Here, the function is called "foldl" ("fold-left") and is the same as the foldl defined in the last lab:

...