Sub topic 13
The abstraction function
This chapter assumes you know what a representation invariant is (a condition every stored value must satisfy), the difference between an ADT's interface and its implementation, and basic Python classes. It builds on the IntSet and stack examples from earlier chapters.
The question the invariant leaves open
A representation invariant tells you which stored values are legal. It does not tell you what a legal value means. Take the list [3, 1, 2] inside an IntSet. The invariant says it has no duplicates, which is fine. But is the object the set {1, 2, 3}? A sequence of three numbers? The set of positions where something happened? The code could mean any of these, and the invariant cannot choose among them.
The abstraction function (AF) answers that question. It is a mapping from a concrete representation value to the abstract value the representation stands for. For IntSet, the AF maps the list [a, b, c] to the set {a, b, c}.
Clients never see the representation. They see only abstract values: sets, stacks, sequences. The AF is the link between the two levels.
What the abstraction function looks like
Write the AF as a comment, next to the invariant, in terms a reader can check against the code. It has a fixed shape: the domain is the set of representation values that satisfy the invariant, and the range is the set of abstract values the specification talks about.
The diagram shows several representation values and the abstract values they map to.
Two properties of this mapping matter in practice.
- It is many-to-one. The lists
[3, 1, 2]and[1, 2, 3]are different representations of the same set. Any operation that treats them differently is a bug, because clients cannot tell them apart in the abstract world. - It is defined only where the invariant holds. A list such as
[1, 1, 2]is outside its domain. If the invariant fails, there is no promise about what the object means. That is why the invariant and the AF are always documented together.
Making the function executable
The AF is usually a comment, but writing it as code is a good way to test your understanding. Here are two implementations of an integer set. They have different invariants and the same AF, and they share one abstract_value method that applies it.
import bisect
class UnsortedIntSet:
"""A set of integers.
AF: the list [a, b, c] represents the set {a, b, c}.
RI: _items contains no duplicates.
"""
def __init__(self):
self._items = []
def add(self, x):
if x not in self._items:
self._items.append(x)
def contains(self, x):
return x in self._items
def abstract_value(self):
return frozenset(self._items)
class SortedIntSet:
"""A set of integers.
AF: the list [a, b, c] represents the set {a, b, c}.
RI: _items is strictly increasing (sorted, no duplicates).
"""
def __init__(self):
self._items = []
def add(self, x):
i = bisect.bisect_left(self._items, x)
if i == len(self._items) or self._items[i] != x:
self._items.insert(i, x)
def contains(self, x):
i = bisect.bisect_left(self._items, x)
return i < len(self._items) and self._items[i] == x
def abstract_value(self):
return frozenset(self._items)
unsorted = UnsortedIntSet()
for x in (3, 1, 2):
unsorted.add(x)
ordered = SortedIntSet()
for x in (1, 2, 3, 2):
ordered.add(x)
print(unsorted._items) # [3, 1, 2]
print(ordered._items) # [1, 2, 3]
print(unsorted.abstract_value() == ordered.abstract_value()) # TrueThe two objects hold different lists, yet they represent the same abstract set. The abstract_value method is the AF made concrete. The tests you write against the specification should talk about this abstract value, not about _items.
The abstraction function defines the meaning of each operation
Every operation is correct or incorrect relative to the AF. For add(x), correctness means this: if the object's abstract value before the call is S, its abstract value afterward is S ∪ {x}. The code does not need to look similar to that statement. It only needs to produce a representation that the AF maps to the right set.
This explains why SortedIntSet.add can insert into the middle of a list while UnsortedIntSet.add appends. Both steps are correct under the same AF. The sorted version also keeps a stronger invariant, which lets contains use binary search.
You can see what the AF does by changing it. Suppose two stack implementations both store their items in a Python list, but one treats the last element as the top and the other treats the first element as the top. The code in push and pop differs between them, because the AF differs.
| Representation | Abstraction function | `push(x)` on the list | `pop()` on the list |
|---|---|---|---|
| `ListStack` | `[a, b, c]` is a stack with `c` on top | `append(x)` | `pop()` removes the last item |
| Front-of-list variant | `[a, b, c]` is a stack with `a` on top | `insert(0, x)` | `pop(0)` removes the first item |
| `LinkedStack` | The chain `head -> a -> b -> c` is a stack with `a` on top | Make a new head node | Move head to the next node |
Each row is a valid implementation, and the AF is what lets you see why the three look so different. The front-of-list variant also costs more, since inserting at the front of a Python list takes O(n). The AF explains the code, and the cost analysis then explains which choice is better.
When the mapping is one-to-one
Many-to-one is common, but not required. You can sometimes choose an invariant that makes the AF one-to-one, so each abstract value has exactly one legal representation.
A rational number type shows this well. Suppose a class stores a numerator and a denominator.
- AF: the pair
(n, d)represents the number n/d. - Without a tight invariant,
(1, 2)and(2, 4)both represent one half. The AF is many-to-one, and equality has to be defined with care. - With the invariant
d > 0 and gcd(n, d) == 1, only(1, 2)is legal. The AF becomes one-to-one, and comparing representations is the same as comparing abstract values.
This is a design trade-off. A strict invariant costs work in every constructor and mutator, because they must normalize their results. In return, equals becomes a simple field comparison and bugs of the "equal but different" kind disappear. A loose invariant makes the operations cheaper to write and pushes the cost into equals and hash.
Using the AF to check equality
Abstract equality is defined through the AF: two objects are equal when their abstract values are equal. For many-to-one representations, that is not the same as comparing fields.
class Fraction:
"""A rational number.
AF: (num, den) represents the number num / den.
RI: den > 0.
"""
def __init__(self, num, den):
assert den > 0
self._num = num
self._den = den
def __eq__(self, other):
if not isinstance(other, Fraction):
return NotImplemented
return self._num * other._den == other._num * self._den
def __hash__(self):
from math import gcd
g = gcd(self._num, self._den)
return hash((self._num // g, self._den // g))
print(Fraction(1, 2) == Fraction(2, 4)) # True
print(hash(Fraction(1, 2)) == hash(Fraction(2, 4))) # TrueThe __eq__ method cross-multiplies, which is a direct translation of "n/d equals n'/d'". The hash reduces by the greatest common divisor first, so equal abstract values always hash the same. If __hash__ hashed the raw pair, equal fractions would land in different buckets and a set would hold both. That is a failure of the equality and hash contract, and its cause is ignoring the AF.
Common mistakes
- Describing the representation instead of the meaning. "AF: the list is
_items" says nothing. State what the list stands for: a set, a sequence, a stack with its top at a named end. - Forgetting that the domain is limited by the invariant. An AF comment that claims to handle every list is wrong whenever the invariant rules some lists out.
- Mutating the representation in a way the AF maps to a different value. An operation labeled "observer" that sorts
_itemsis harmless under the set AF but changes the abstract value under a sequence AF. Check each operation against the AF you documented, not the one you assume. - Comparing representations when you mean to compare values. Comparing
_itemsdirectly says that[3, 1, 2]and[1, 2, 3]are different sets.
Where this leads
With an invariant and an AF, you can state what it means for an implementation to be correct. Every legal representation maps to an abstract value, and every operation moves that value as the specification demands. The next chapter looks at how this argument breaks when internal state leaks to clients, which is called representation exposure.
Exercise
A Stack is stored in a Python list _items, with the invariant that _items is a list. One developer writes the AF "the last element is the top". Another writes "the first element is the top". Both have working push and pop. Explain why their code differs, and name one cost consequence of the second choice.
Show answer
The AF fixes which end of the list is the top, so push and pop must operate on that end. With the last element as the top, push is append(x) and pop is pop(). With the first element as the top, push is insert(0, x) and pop is pop(0). Both are correct under their own AF. The second choice is more expensive: inserting or removing at the front of a Python list shifts every other element, so each operation takes O(n) instead of amortized O(1).
Exercise
A Fraction class stores (num, den) with the invariant den > 0. Is its abstraction function one-to-one? If not, give two representation values that map to the same abstract value, and name an invariant that would make the function one-to-one.
Show answer
It is not one-to-one. (1, 2) and (2, 4) both map to the number one half. Adding the invariant gcd(num, den) == 1 (together with den > 0) leaves (1, 2) as the only legal representation of one half, which makes the AF one-to-one. The cost is that every constructor and operation must reduce its result.