This is the lecture note of CS61A - Lecture 11.
We've already learnt function, which is an abstraction of computation process.
In today's lecture, let's learn a new way of abstaction —— data abstraction.
Data Abstraction
Most value are compound values.
Let's look at an example.
1 | # Rational arithmetic |
rational(n, d)
: returns a rational numbernumer(x)
: returns the numeratordenom(x)
: returns the denominator
These three functions implement an abstract data type for rational numbers.
Q: How to implement these three functions?
1 | # How to represent data? |
The above code need some improvements. Think about the following examples:
- 3/2 * 5/3 = 15/6 = 5/2
- 2/5 + 1/10 = 25/50 = 1/2
The numerator and denominator of a rational number should be relatively prime.
1 | # Improved implementation |
Abstraction Barriers
The purpose of maintaining abstraction barriers, is so that you can change your data representation without having to rewrite your entire program.
Let's take a look at another example.
Here, we use function instead of built-in list to implement rational data. We only change data representation whereas keeping data manipulations. The outcome is still correct!
1 | # Functional implementation |
Dictionaries
A dictionary allows you to associate values with keys.
👻 Dictionary doesn't have order inheritantly.
1 | 'I': 1, 'V': 5, 'X': 10} numerals = { |
Dictionary Comprehension
1 | for x in range(10) if x < 5} {x: x*x |