CPSC 110 Lecture Notes - Lecture 25: Foreach Loop, American Broadcasting Company, Natural Number
CPSC 110 verified notes
25/26View all
Document Summary
(require 2htdp/image) (require spd/tags) (@signature (listof number) -> number) [else (+ (first lon) (sum1 (rest lon)))])) (@template use-abstract-fn) (define (sum2 lon) (foldr + 0 lon)) (@template (listof number) accumulator) (define (sum3 lon0) ;; acc is number: sum of numbers in lon0 seen so far. ;; (sumacc (list ) 14) (local [(define (fn-for-lon lon acc) (cond [(empty? lon) acc] [else (fn-for-lon (rest lon) (+ acc (first lon)))]))] (fn-for-lon lon0 0))) Note that sum3 is tail recursive (foldr is not). ;; today we introduce a 4th way - using for-each loops. ;; is rather like map except that it calls the function for effect rather. ;; than to do something with the value produced by the function. ;; here"s the template for designing with the for-each construct: (define (fn lox) ;; acc is : (local [(define acc )] (begin (for-each lox) ; can use a expression or locally defined function ( acc))))