CSC151 2010S, Class 53: Objects in Scheme Overview: * Motivating problems: Circles, turtles, and counters. * Building and using compound values. * Objects: A new approach to compound values. * Creating objects in Scheme. Admin: * Lecture day! * EC for Student Art Salon in Vern's place. * I intend to go over exam 3 in class tomorrow. I expect you all to be there. * Special EC for filling out the end-of-semester RISC survey at http://www.grinnell.edu/academic/psychology/faculty/dl/risc/. * EC surveys to be distributed later this week. Some problems in data and computation * Image problem one: We want to think about drawing with circles * But we're impure * A circle is something with * Radius * Center * Color * You can change circles! (circle-enlarge! circle amt) (circle-recolor! circle newcolor) (circle-shove! circle direction amount) * Image problem two: How could we write our own turtles? * What information do we need to store? * Direction * Image on which they are placed * Brush with which they draw * Color * Position (row and column) * Brush up/down * We also name turtles * Unrelated problem: We want to count the number of times we call cons (or some other procedure) * And we want to generalize this idea into a "counter" type These are all problems with what is called state! * You may remember from exam one that pure functional languages are stateless. * But Scheme is not a pure functional language How might we represent a turtle, counter, or circle so that we can change the information? * Circle: row, column, radius, and color * We could put them in a list or vector. * Position 0 is the row * Position 1 is the column * Position 2 is the radius * Position 3 is the color (define circle1 (list 10 10 50 "red")) (define circle2 (vector 30 40 100 "blue")) * Why use the vector? * It's faster to access the third element * You can't change the size, so it feels more solid * YOU CAN CHANGE THE VALUES! Problems? * If we want shapes other than circles, it may be hard to generalize our code. * Ellipses will require five-element vectors * Impurity can make life hard * We need a clone operation * If we do (define c1 (....)) (define c2 c1) What is the relationship between changes to c1 and changes to c2? A big disadvantage of stateful languages * Clueless bozos can change the vector inappropriately How to limit what clueless users can do! (define circle1 (let ((contents (vector 50 10 24 "green"))) (lambda (change amt) (cond ((eq? change "get-color") (vector-ref contents 3)) ((eq? change "recolor") (vector-set! contents 3 amt)))))) Requires a lot of other changes to the other procedures, but useful A new model of programming, called object-oriented programming * Objects *encapsulate* their state * They can change them, but others can't directly accdess the state * They provide both state and capabilities * It turns out that objects also provide a nice model of the world