;;; ========================================== ;;; CMPU-145, Spring 2013 ;;; Lab 1 Solutions ;;; Feb. 4, 2013 ;;; ========================================== (load "asmt-helper.txt") (header "lab1" "Solutions!") ;;; ------------------------- ;;; PROBLEM 0: CONS, LIST and APPEND ;;; ------------------------- (problem "0: CONS, LIST and APPEND") (tester '(cons 1 1)) (tester '(cons 1 '(1 2))) (tester '(cons '(1 2) 1)) (tester '(cons '(1 2) '(1 2))) (newline) (tester '(list 1 1)) (tester '(list 1 '(1 2))) (tester '(list '(1 2) 1)) (tester '(list '(1 2) '(1 2))) (newline) (tester '(append '(1 2) '(1 2))) ;; NOTE: Can only apply APPEND to LISTS!! ;;; ----------------------------- ;;; PROBLEM 1: MAP ;;; ----------------------------- (problem "1: MAP") (tester '(map even? '(1 2 3 4 5))) (tester '(map (lambda (x) (* x x)) '(1 2 3 4 5))) (tester '(map first '((1 2 3) (4 5) (6 7 8 9)))) (tester '(map rest '((1 2 3) (4 5) (6 7 8 9)))) (tester '(map (lambda (subbie) (list (first subbie) (second subbie))) '((1 2 3) (4 5) (6 7 8 9)))) (newline) ;;; TRICKY ;;; ----------------------------------------- ;;; INPUTS: ITEM, an item ;;; LOL, a list of lists ;;; OUTPUT: A list-of-lists just like LOL, except that each ;;; subsidiary list has been prepended with ITEM. (define tricky (lambda (item lol) ;; Use MAP to apply a LAMBDA function to the List-of-Lists ;; The LAMBDA function conses ITEM onto each SubList (map (lambda (subbie) (cons item subbie)) lol))) (tester '(tricky 1 '((2 3) (0 0 0) (4 5 6) (3)))) (tester '(tricky 3 '((4 5 6) (30 300 3000) ()))) ;;; ---------------------------------- ;;; PROBLEM 2: LET* ;;; ---------------------------------- (problem "2: LET*") (tester '(let* ((x 2) (y (* x x)) (z (+ x y)) (w (* z 10))) (list x y z w))) (newline) ;;; FUNKY ;;; ----------------------------------------- ;;; INPUT: LISTY, a list of integers ;;; SIDE EFFECT: Prints out LISTY-ONE, LISTY-TWO and LISTY-THREE ;;; where LISTY-ONE is the same as LISTY except that each ;;; number has been incremented by one; ;;; LISTY-TWO is the same as LISTY-ONE except that ;;; each element has been squared; ;;; LISTY-THREE is a list of booleans: #t if the ;;; corresponding element of LISTY-TWO is even, ;;; #f otherwise. ;;; OUTPUT: LISTY-THREE (define funky (lambda (listy) (let* ((listy-one (map 1+ listy)) (listy-two (map (lambda (x) (* x x)) listy-one)) (listy-three (map even? listy-two))) ;; Print out a bunch of stuff to the interactions window (newline) ;; just to make it look nicer (printf "listy-one: ~A~%" listy-one) (printf "listy-two: ~A~%" listy-two) (printf "listy-three: ~A~%" listy-three) ;; Then return LISTY-THREE as the output value of the LET*, and hence of the function listy-three))) (tester '(funky '(1 2 3 4 5))) (newline) (tester '(funky '(1 3 5 7 9))) (newline) (tester '(funky '(10 100 1000 10000)))