people properties: 'josh 'blond-haired 'blue-eyed 'fair-skinned 'male 'big-feet 'evelyn 'black-haired 'green-eyed 'black-skinned 'female 'small-feet ball position: 12 14 16 26 20 38 At what rate is the ball rolling? 4 in the x direction, 12 in the y direction ball speed: 4 12 again pairs of numbers
So here are some Scheme lists:
empty (cons 3 empty) (cons 'blond empty) (cons 'black empty) (cons 4 (cons 3 empty)) ^^^^^^^^^^^^^^ is a list by above argument (cons 'josh (cons 'blond empty)) ^^^^^^^^^^^^^^ is a list by above argument (cons 'evenlyn (cons 'black empty)) ^^^^^^^^^^^^^^ is a list by above argumentWhat items are on these lists?
(define (distance a-point) ...)What do we need to do here? Aha, we need to find out the numbers on the list. How do we do that?
We have seen how to construct lists. Now we need to destruct them. We get two operations. If x is a constructed list, (first x) and (rest x) can extract some information: the item and the list, respectively, that cons glued together.
(first x) = 3 if x = (cons 3 (cons 4 empty)) if x = (cons 4 empty) if x = (cons 4 L) (rest x) = (cons 4 empty) if x = (cons 3 (cons 4 empty)) (rest x) = empty if x = (cons 4 empty) (rest x) = L if x = (cons 4 L)Exercise: if x is guaranteed to be a list with two, three, four items, how do I get back the second item:
(first (rest x)) (first (rest (rest x))) (first (rest (rest (rest x))))
(define (distance-to-origin a-point) (sqrt (+ (square (first a-point)) (square (first (rest a-point))))))Here is how we calculate with this thing:
(distance-to-origin (cons 3 (cons 4 empty))) = (sqrt (+ (square (first (cons 3 (cons 4 empty)))) (square (first (rest (cons 3 (cons 4 empty))))))) = (sqrt (+ (square 3) (square (first (rest (cons 3 (cons 4 empty))))))) = (sqrt (+ (square 3) (square 4))) = (sqrt (+ 9 16)) = 5
;; A point is a list of two numbers: ;; (cons number (cons number empty)) (define (make-point x y) (cons x (cons y empty))) (define (point-x a-point) (first a-point)) (define (point-y a-point) (first (rest a-point)))How do these things interact:
(point-x (make-point 3 4)) = 3 (point-y (make-point 3 4)) = 4 ...
(define (distance-to-origin a-point) (sqrt (+ (square (point-x a-point)) (square (point-y a-point)))))Little homework:
(distance-to-origin (make-point 3 4))