CSC 160 Computer Programming for Non-Majors Chapter 6: Structures Prof. Adam M. Wittenstein
Atomic vs. Compound Data So far our input has been a single number. Usually the input is a piece of data that represents an object with many properties. For example, a person’s personnel record will contain date of birth, salary, name, social security number, etc. Scheme provides many ways to do this. In this chapter, we will see one way to do this – Structures.
Section 6.1: Structures
Posns: A First Structure Why carry a dozen loose oranges when I could put them in a bag? Bag: one object that contains several others posn: one object that contains two others (x coordinate and y coordinate) Posns are actually a predefined data type in Scheme, just like numbers and images.
Built-in functions involving posns make-posn : number number -> posn posn-x : posn -> number posn-y : posn -> number posn? : object -> boolean
Working with posns (define here (make-posn 5 12)) (posn-x here) "should be" 5 (posn-y here) "should be" 12 (posn? here) "should be" true (posn? 7) "should be" false
Common mistakes with posns (posn-x 5) posn-x expects to be given a posn; it returns a number. (posn 5 12) There is no posn function, but there is a make-posn function. (make-posn here (5 12)) make-posn does not define a new variable; it only creates a posn. What you do with that posn (return it, store it in a variable, throw it away…) is up to you. here-x The way to extract the x-coordinate of here is by using the posn-x function: (posn-x here)
Exercise Evaluate the following expressions: (distance-to-0 (make-posn 3 4)) (distance-to-0 (make-posn 3 4)) (distance-to-0 (make-posn (* 2 3) (* 2 4))) (distance-to-0 (make-posn (* 2 3) (* 2 4))) (distance-to-0 (make-posn 12 (- 6 1))) (distance-to-0 (make-posn 12 (- 6 1))) by hand. Show all steps. Assume that sqr performs its computation in a single step. Check the results with DrScheme's stepper.
Exercise Define an appropriately named variable for the posn (0, 0) Define an appropriately named variable for the posn (0, 0) Recall the Scheme syntax rule for this: (define VARIABLE-NAME its-value)
In summary… You have seen how to work with a structure that is defined. Next time… Writing functions with posns.