SICP
Chapter 2.1
Introduction to Data Abstraction
-
Build abstractions by combining data to form compound data
(define a (cons x y)) (car a) ; x (cdr a) ; y
-
Programs should make no assumptions about the data and its implementation details
-
The concrete data representation should be independent of the programs using the data
-
The interface between these two components are a set of procedures selectors and constructors
(define (make-rat x y) (cons x y)) (define (numer rat) (car rat)) (define (denom rat) (cdr rat))
-
Example of adding rational numbers
- Use relationships to define a procedure, not the representation of a rational number
- (n1 / d1) + (n2 / d2) = (n1 * d2 + n2 * d1) / (d1 * d2)
(define (add-rat x y) (make-rat (+ (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y))))
- Use relationships to define a procedure, not the representation of a rational number
Abstraction Barriers
- The idea of data abstraction is to identify for each type of data object a basic set of operations in terms of which all manipulations of data objects of that type will be expressed
- Only those set of operations should be used to manipulate the data
- Barriers for rational number example:
- Programs that use rational numbers
- Rational numbers in problem domain: add-rat, sub-rat, etc.
- Rational numbers as numerators and denominators: make-rat, numer, denom**
- Rational numbers as pairs: cons, car, cdr
- Some implementation for pairs
What is meant by data?
- Constructors and selectors must fulfill conditions to form a suitable basis for representations of data
- Ex. make-rat, numer and denom must satisfy the following condition
- For any integer n and any non-zero integer d, if x is (make-rat n d)
- (numer x) / (denom x) = n / d
- Ex. make-rat, numer and denom must satisfy the following condition