Functional Problem Solving (CSC 151 2014S) : Outlines

Outline 52: Objects in Scheme


Held: Friday, 2 May 2014

Back to Outline 51 - Project Assessment: Algorithms. On to Outline 53 - Objects in Scheme, Continued.

Summary

We begin to explore objects in Scheme. Objects encapsulate data and the procedures that work with those data.

Related Pages

Overview

Administrivia

Upcoming Work

Extra Credit

Motivating Problems

Compound Values

Objects: Encapsulating Values and Operations

Objects in Scheme

(define greeter
  (lambda (message)
    (cond 
      ((eq? message ':enter) (display "Hello") (newline))
      ((eq? message ':leave) (display "Goodbye") (newline))
      (else (error "Unknown Message")))))
> (greeter ':enter)
Hello
> (greeter ':leave)
Goodbye
> (greeter ':sleep)
Unknown Message

Adding State

(define fixed-value
  (let ((value 5))
    (lambda (message)
      (cond
        [(eq? message ':get) value]
        [else (error "fixed-value:" "unknown message")]))))
(define incrementable-value
  (let ((value (vector 0)))
    (lambda (message)
      (cond
        [(eq? message ':get) 
         (vector-ref value 0)]
        [(eq? message ':add1!)
         (vector-set! value 0 
                      (+ 1 (vector-ref value 0))))
        [else (error "fixed-value:" "unknown message")]))))
> (incrementable-value ':get)
0
> (incrementable-value ':add1!)
> (incrementable-value ':get)
1

Lab


Samuel A. Rebelsky, rebelsky@grinnell.edu

Copyright (c) 2007-2014 Janet Davis, Samuel A. Rebelsky, and Jerod Weinman. (Selected materials are copyright by John David Stone or Henry Walker and are used with permission.)

Creative Commons License

This work is licensed under a Creative Commons Attribution 3.0 Unported License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc/3.0/ or send a letter to Creative Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105, USA.