;; ;; FILE: session06.rkt ;; AUTHOR: Eugene Wallingford ;; DATE: 2023/02/02 ;; COMMENT: You can use this file as an example of how to organize ;; your source file for Homework 3 and beyond. The code ;; through the acronym section is similar to a homework: ;; a header block, language and require expressions, and ;; a solution to a problem. The solution includes a main ;; procedure, a helper procedure, and some test cases. ;; ;; MODIFIED: ;; CHANGE: ;; #lang racket (require rackunit) (provide acronym) ;; ------------------------- ;; opening exercise: acronym ;; ------------------------- (define first-char (lambda (str) (string-ref str 0))) (define acronym (lambda (list-of-strings) (apply string (map first-char list-of-strings)))) ;; test cases (define acronym01 (acronym '("University" "California" "Santa" "Barbara"))) (define acronym02 (acronym '("The" "Artist" "Formerly" "Known" "As" "Prince"))) (define acronym03 (acronym '("University" "Northern" "Iowa"))) (check-equal? (acronym '("Eugene" "Wallingford")) "EW") (check-equal? acronym01 "UCSB") (check-equal? acronym02 "TAFKAP") (check-equal? acronym03 "UNI") ;; ------------------------------- ;; functions that return functions ;; ------------------------------- (define add6 (lambda (x) (+ x 6))) (define add (lambda (n) (lambda (m) (+ m n)))) (check-equal? ((add 5) 12) 17) (check-equal? ((add -100) 142) 42) (check-equal? (map (add 6) '(1 4 9 16 25)) '(7 10 15 22 31)) ;(define add6 (add 6)) ;; ------------------------------------- ;; another example: computing fuel needs ;; ------------------------------------- ; We have a file of module masses, one per line: ; ; 12 ; 14 ; 1969 ; 100756 ; Racket has a function to read this file into a list of strings: ; ; > (file->lines "modules.txt") ; '("12" "14" "1969" "100756") ; (map string->number ; (file->lines filename)) (define mass->fuel (lambda (m) (- (quotient m 3) 2))) ; (map mass->fuel ; (map string->number ; (file->lines filename))) ; ; (apply + ; (map mass->fuel ; (map string->number ; (file->lines filename)))) (define total-fuel (lambda (filename) (apply + (map mass->fuel (map string->number (file->lines filename)))))) (check-equal? (total-fuel "modules.txt") 34241) ; Thinking more functionally: how do we eliminate the dependence that ; total-fuel has on the outside world? ;; -------------------------- ;; functional style a la bash ;; -------------------------- ; cat session06.rkt | grep lambda | wc -l ;; -------------- ;; variable arity ;; -------------- (define average ; This is from Session 5. (lambda numbers ; Notice: there are no parentheses around the parameter. (/ (apply + numbers) (length numbers)))) ; test cases (define 1-to-100 (range 1 101)) (define the-roots (map sqrt 1-to-100)) (check-equal? (apply average 1-to-100) 101/2) (check-equal? (apply average the-roots) 6.714629471031477) ;; ----------- ;; end of file ;; -----------