;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; U. C. Berkeley ;; ;; EECS Computer Science Division ;; ;; CS3 Lecture 21 Answers ;; ;; (Input / Output) ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Formatting ... ;; We'll use [ ] to highlight what the user types to (read), ;; ==P to indicate what the computer PRINTS, and ;; ==> to indicate the return value (as always) ;;;;;;;;;; ;; STRINGS ;;;;;;;;;; "Go Bears" ;; ==> "Go Bears" (string? "Go Bears") ;; ==> #t (string-length "Go Bears") ;; ==> 8 ;;;;;;;;; ;; OUTPUT ;;;;;;;;; (display 'a-symbol) ;; ==P a-symbol ;; ==> 8 (write 'a-symbol) ;; ==P a-symbol ;; ==> 8 (display "a string") ;; ==P a string ;; ==> 8 (write "a string") ;; ==P "a string" ;; ==> 10 ;;;;;;;;;;; ;; FOR-EACH ;;;;;;;;;;; (for-each abs '(-1 2 -3.4 -5/6)) ;; ==P ;; ==> #[undefined] (define (print-list-one-elt-per-line L) (for-each (lambda (elt) (display elt) (newline)) L) 'done) (print-list-one-elt-per-line '("Cal Bears" (we are) Number 1)) ;; ==P Cal Bears ;; ==P (we are) ;; ==P number ;; ==P 1 ;; ==> done ;;;;;;;;;;;;;;; ;; IF AND BEGIN ;;;;;;;;;;;;;;; ;; : (big-game-winner-prediction 'cal) ;; ==P Party on! You were right that ;; ==P Cal will win the Big Game! ;; ==> done! ;; ;; : (big-game-winner-prediction 'stanfurd) ;; ==P Bzzt! Thanks for trying... ;; ==P stanfurd will not win the Big Game, Cal will! ;; ==> done! ;; ;; : (big-game-winner-prediction 'eat-my-shorts) ;; ==P Bzzt! Thanks for trying... ;; ==P eat-my-shorts will not win the Big Game, Cal will! ;; ==> done! ;; Here is the repaired version, the old version didn't even ;; let us define the function! (define (big-game-winner-prediction team) (if (equal? team 'cal) ;; They predicted Cal (begin (display "Party on! You were right that") (newline) (display "Cal will win the Big Game!")) ;; They didn't predict Cal (begin (display "Bzzt! Thanks for trying...") (newline) (display team) (display " will not win the Big Game, Cal will!"))) (newline) 'done!) ;;;;;;; ;; READ ;;;;;;; (read) ;; [42] ;; ==> 42 (read) ;; [cs3] ;; ==> cs3 (read) ;; [cs3 is the best class] ;; ==> class (read) ;; ["cs3 is the best class"] ;; ==> "cs3 is the best class" (read) ;; [(cs3 is the best class)] ;; ==> (cs3 is the best class) (read) ;; [(+ 1 1) (+ 150 150)] ;; (+ 150 150) ;;;;;;;;;;;;;;;;;; ;; GET-VALID-INPUT ;;;;;;;;;;;;;;;;;; ;; read until input is in valid-input ;; print intro message to user first - prompt (define (get-valid-input valid-input message) (display message) (display " ") (let ((input (read))) (cond ((member input valid-input) input) (else (display "Bad value entered: ") (display input) (newline) (get-valid-input valid-input message))))) : (get-valid-input '(yes yep sure uh-huh) "Is CS3 cool?") ;; ==P Is CS3 cool? [maybe] ;; ==P Bad value entered: maybe ;; ==P Is CS3 cool? [well, I don't know...] ;; ==P Bad value entered: know... ;; ==P Is CS3 cool? [yes it is] ;; ==P Bad value entered: is ;; ==P Is CS3 cool? [yes] ;; ==> yes