(load "tester.scm") ;; ;; foldr ;; ;; Usage: (foldr f unit List) ;; ;; What it does: foldr applies the BINARY function f ;; starting with the value unit ;; pairwise through the list List ;; and evaluates to a single value (not a list) ;; ;; With each element, it accumulates the running value.... ;; the result at the end is the fully accumulated value. ;; ;; For example, (foldr + 0 '(4 5 6 1 19 7)) does the following: ;; ;; 0 + 4 + 5 + 6 + 1 + 19 + 7 ;; ;; and evaluates to the value 42. ;; ;; foldr's name in Python is reduce ;; ;; Check out these examples: ;; understanding foldr... (test (foldr + 0 '(4 5 6 1 19 7)) 42) ;; sums the list! ;; understanding foldr MORE!... (test (foldr * 1 '(4 5 6 1 19 7)) 15960) ;; multiplies the list! ;; even more foldr... ;; NOTE: +inf.0 is Scheme's syntax for positive infinity ;; MY APOLOGIES -- in the email I missed that this converts to floating point.. (test (foldr min +inf.0 '(4 5 6 1 19 7)) 1.0) ;; finds the min of the list! ;; even more foldr... ;; NOTE: -inf.0 is Scheme's syntax for negative infinity ;; MY APOLOGIES -- in the email I missed that this converts to floating point.. (test (foldr max -inf.0 '(4 5 6 1 19 7)) 19.0) ;; finds the max of the list! ;; we can use our own functions with foldr, such as ;; this shorter-list function (define (shorter-list ListA ListB) (if (< (length ListA) (length ListB)) ListA ;; ListA is shorter! ListB ;; ListB is shorter! )) ;; check if shorter-list is working... (test (shorter-list '(1 2 3) '(1 2)) '(1 2)) ;; use it with foldr to define shortest-list-of-all... ;; don't input the empty list as ListOfLists! It will break. (define (shortest-list-of-all ListOfLists) (foldr shorter-list (first ListOfLists) (rest ListOfLists))) ;; test it out (test (shortest-list-of-all '( (1 2 3) (1) (1 2 3 4) )) '(1)) ;; ;; map ;; ;; Usage: (map f List) ;; ;; What it does: foldr applies the UNARY function f ;; to each element of the list List ;; yielding a new list ;; ;; For example, (map length '( (1 2 3) (1) (1 2 3 4) )) ;; evaluates to ;; ( 3 1 4 ) ;; ;; There is map in Python, too. ;; ;; Check out these examples: ;; example of map (test (map length '( (1 2 3) (1) (1 2 3 4) )) '(3 1 4)) ;; we can define our own function... a simple letter-scorer: (define (score-letter input-letter) (let* ( (alist '((#\a 20) (#\b 1))) ;; our association list! (found (assoc input-letter alist)) ;; found is #f or the matching sublist ) (if found (second found) ;; return the letter's score 0) ;; not found? we give it zero )) ;; check our new function (test (score-letter #\a) 20) (test (score-letter #\c) 0) ;; a convenient name for summing a list of numbers with foldr... (define (sum List) (foldr + 0 List)) ;; a second example of map... (test (sum (map score-letter (string->list "baseball"))) 42) ;; see if you can tell why the answer above is 42...