Abstract Data Types

advertisement
Data type:
Collection of values and a set of operations on those values
Abstract Data Type (ADT):
Description of a data type
The basic mathematical concept that defines a data type
Definition of an ADT is not concerned with the implementation details
A particular ADT may or may not be able to be implemented on in a particular
environment
An Example:
ADT of Rational Numbers:
/* value definition */
abstract typedef < int, int> Rational;
condition Rational[1] = 0;
/* operator definition */
abstract equal(a,b)
Rational a, b;
postcondition equal = (a[0]*b[1] == b[0]*a[1]);
abstract Rational makerational(a.b)
int a,b;
precondition b!= 0;
postcondition makerational[0]*b ==a*makerational[1];
abstract Rational add(a,b)
Rational a, b;
postcondition add = [a[0]*b[1] + b[0]*a[1], a[1]*b[1]];
abstract Rational mult(a,c)
Rational a, b;
postcondition mult = [a[0]*b[0], a[1]*b[1]];
Rational Numbers in C:
typedef struct Rational
{
int numerator;
int denominator;
} Rational;
#define TRUE 1
#define FALSE 0
int equal (Rational *rat1, Rational *rat2)
{
Rational r1, r2;
reduce (rat1, &r1);
reduce (rat2, &r2);
if(r1.numerator == r2.numerator && r1.denominator == r2.denominator)
return (TRUE);
return FALSE;
}
Sequence as Value Definition:
abstract typedef <<tp>> adt1;
abstract typedef <tp0, tp1, tp2, … , tpn> adt2;
abstract typedef <<tp, n>>;
abstract typedef << int>> intseq;
abstract typedef <int, char, float> aseq;
abstract typedef <<int, 10>> array
abstract typedef << , 2>> pair
adt1 is a sequence of items each of type
tp
adt2 is a sequence of items whose
values are sequences of fixed length
with each element of specific type
adt3 is a sequence of length n, all of
whose elements are of type tp
Sequence of integers of any length
Sequence of length 3 consisting of an
integer, character, and a float
Sequence of 10 integers
Arbitrary sequence of length 2
len(S)
Length of seqence
equal(S, T)
two sequences are equal if each element of the first is equal to the corresponding
element of the second
sub(S, i, j)
a subsequence is a contiguous portion of a sequence. If S is a sequence then
sub(S, i, j) refers to the subsequences of S starting at position I in S and consisting
of j consecutive elements.
concat(S, T)
concatenation of two sequences S and T written as S+T is the sequence consisting
of all the elements of S followed by all the elements of T.
insert(S, i, x)
sequence S with the element x inserted immediately following position I, or into
the first position if I = -1. All subsequent elements are shifted by one position.
insert(S, i, x) = sub(S, 0, i+1) +<x> sub(S,i+1, len(S)-(i+1))
delete(S, i)
sub(S,0,i) + sub(S,i+1,len(S)-(i+1))
Download