;; The first three lines of this file were inserted by DrRacket. They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-intermediate-reader.ss" "lang")((modname main) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) ; [Number] l -> Number ; Greatest common denominator of a list of positive integers. (define (gcdl l) (local [(define ln (length l))] (cond [(= 0 ln) (error "No denominator common among nothing.")] [(= 1 ln) (first l)] [(= 2 ln) (gcd (first l) (second l))] [else (gcdl (cons (gcd (first l) (second l)) (rest (rest l))))]))) (check-error (gcdl '())) (check-expect (gcdl '(1)) 1) (check-expect (gcdl '(1 2 3)) 1) (check-expect (gcdl '(6 18 12)) 6) (check-expect (gcdl '(100 50 2)) 2) ; [T] l -> [[T]] ; Groups equivalent consecutive elements of a list into their own list. (define (pack l) (local [; [[T]] l -> T ; Gets the first element of the first element of l. (define (first-twice l) (first (first l))) ; This could also be replaced with caar(). ; [[T]] l -> [[T]] ; Repeat twice the first element of the first element of l. (define (twice-first l) (cons (cons (first-twice l) (first l)) (rest l))) ; [T] l, [[T]] m -> [[T]] ; Inserts first element of list l in new first list in list of lists m. (define (enlist l m) (cons (list (first l)) m)) ; [T] l, [[T]] a -> [[T]] ; Groups all consecutive elements equivalent to the first element of the first element of a. ; What's being accumulated: a reversed packed list. ; How it's initialized: empty. ; How it's it updated: cons to beginning. ; How it's used in the final answer: reverse. (define (consequivalent l a) (cond [(empty? l) a] [(empty? a) (consequivalent (rest l) (enlist l empty))] [(equal? (first l) (first-twice a)) (consequivalent (rest l) (twice-first a))] [else (consequivalent (rest l) (enlist l a))]))] (reverse (consequivalent l '())))) (check-expect (pack '()) '()) (check-expect (pack '(1 2 3)) '((1) (2) (3))) (check-expect (pack '(1 1 1 2 3 3 3 4 4 2 2 5)) '(( 1 1 1) (2) (3 3 3) (4 4) (2 2) (5))) ; Number start, Number lower, Number upper, [Number] l -> Boolean ; Determines if an object that begins at the starting location and then moves delta by delta ever ever steps outside of the bounds (inclusive). (define (out-of-bounds? start lower upper l) (or (< start lower) (> start upper) (and (not (empty? l)) (out-of-bounds? (+ start (first l)) lower upper (rest l))))) (check-expect (out-of-bounds? 0 -1 2 '(0 -2 3 -4 6)) #t) (check-expect (out-of-bounds? 0 -1 1 '(1)) #f) (check-expect (out-of-bounds? 0 -1 1 '()) #f) (check-expect (out-of-bounds? 0 1 2 '()) #t) (check-expect (out-of-bounds? 0 0 0 '()) #f)