Ch.8: Abstract Datatypes Plan
Properties of counters
We might also require that our representation should satisfy some
- bvious properties. The following should hold for any counters c1 and
c2: is_zero(make_counter()) not is_zero(inc c) c1 = c2 iff inc(c1) = inc(c2) c1 = c2 implies that dec(c1) = dec(c2) c1 = dec(inc(counter)) Questions:
- do the requirements above allow us to show that inc(c1) = c1 holds
for no counter c1?
- does the requirements above state everything we would like to be true
for counters?
Sven-Olof Nystr¨
- m/IT Dept/Uppsala University
FP
8.2
Ch.8: Abstract Datatypes Plan
Chapter 8 Abstract Datatypes
An abstract data type is a description of a common representation of data. Abstract data types are one of the most important concepts in all programming, because they allow building representations for complex data from simpler parts. Also, looking at abstract data types gives us an opportunity to review concepts such as functions on lists, datatypes, polymorphism, currying, higher-order functions and show some the functional implementation of some algorithms. A simple example: A counter. We need a few operations:
- make_counter : () -> counter
- inc : counter -> counter
- dec : counter -> counter
To keep things simple, assume that when a counter reaches zero, it stays at zero if we keep decrementing it. More operations:
- is_zero : counter -> bool
- = : counter * counter -> bool
Let’s assume that counters can be compared for equality.
Sven-Olof Nystr¨
- m/IT Dept/Uppsala University
FP
8.1
Ch.8: Abstract Datatypes Plan
Counters as lists
We could do something more imaginative: type counter = unit list fun make_counter () = [] fun inc c = ()::[] fun dec c = if c = [] then [] else tl c fun is_zero c = null c
Sven-Olof Nystr¨
- m/IT Dept/Uppsala University
FP
8.4
Ch.8: Abstract Datatypes Plan
Implementing counters
type counter = int fun make_counter () = 0 fun inc c = c+1 fun dec c = if c = 0 then 0 else c-1 fun is_zero c = c = 0 (Check that this representation satisfies the requirements)
Sven-Olof Nystr¨
- m/IT Dept/Uppsala University
FP
8.3