;; ;; FILE: 01-opening-exercise.rkt ;; AUTHOR: Eugene Wallingford ;; DATE: 2023/02/07 ;; COMMENT: Improving a file originally written in 2020. ;; #lang racket ;; -------------------------------------------------- ;; set-up for exercise ;; -------------------------------------------------- ; our data: 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") (define modules (file->lines "modules.txt")) ; our helper function: convert a mass to an amount of fuel: (define mass->fuel (lambda (m) (- (quotient m 3) 2))) ;; -------------------------------------------------- ;; solution with anonymous lambda ;; -------------------------------------------------- ; (map (lambda (module) ; (mass->fuel (string->number module))) ; modules) ;; -------------------------------------------------- ;; solution with named lambda ;; -------------------------------------------------- (define module->fuel (lambda (module) (mass->fuel (string->number module)))) ; (map module->fuel modules) ;; -------------------------------------------------- ;; using the result to compute other solutions ;; -------------------------------------------------- ; (apply + (map module->fuel modules)) (define total-fuel (lambda (filename) (apply + (map module->fuel (file->lines filename))))) ; We can use other reducing functions, too: ; (apply min (map module->fuel modules)) ;; -------------------------------------------------- ;; A sequence of maps can usually be collapsed into ;; a single map with a more powerful helper function. ;; Consider Problem 5 on Homework 3... ;; --------------------------------------------------