<<

Generic Programming

y

David R Musser Alexander A Stepanov

Rensselaer Polytechnic Institute HewlettPackard Lab oratories

Computer Science Department Software Technology Lab oratory

Amos Eaton Hall Post Oce Box

Troy New York Palo Alto California

Abstract

Generic programming centers around the idea of abstracting from concrete ef

cient to obtain generic algorithms that can b e combined with dierent

data representations to pro duce a wide variety of useful software For example a

class of generic sorting algorithms can b e dened whichwork with nite sequences

but which can b e instantiated in dierentways to pro duce algorithms working on

arrays or linked lists

Four kinds of abstractiondata algorithmic structural and representational

are discussed with examples of their use in building an Ada of software

comp onents The main topic discussed is generic algorithms and an approachto

their formal sp ecication and verication with illustration in terms of a partitioning

such as is used in the quicksort algorithm It is argued that generically

programmed software comp onent libraries oer imp ortantadvantages for achieving

software pro ductivity and reliability

This pap er was presented at the First International Joint Conference of ISSAC and AAECC

Rome Italy July ISSAC stands for International Symp osium on Symb olic and Algebraic

Computation and AAECC for Applied Algebra Algebraic Algorithms and Error Correcting Co des It

was published in Lecture Notes in Computer Science SpringerVerlag pp

y

The rst authors work was sp onsored in part through a sub contract from Computational Logic

Inc whichwas sp onsored in turn by the Defense Advanced Research Pro jects Agency ARPA order

The views and conclusions contained in this do cument are those of the authors and should not

be interpreted as representing the ocial p olicies either expressed or implied of the Defense Advanced

Research Pro jects AgencytheUSGovernment or Computational Logic Inc i

ii CONTENTS

Contents

Intro duction

Classication of Abstractions

Data abstractions

Algorithmic abstractions

Structural abstractions

Representational abstractions

Algorithmic Abstractions

A Generic Partition Algorithm

Abstract Algorithm Sp ecication and Verication

Basic sp ecication of Partition

Obtaining a sequence satisfying Test

Correctness when Swap is an assignment op eration

Correctness of the b o dy of Partition

Conclusion

Intro duction

By generic programming we mean the denition of algorithms and data structures at

an abstract or generic level thereby accomplishing many related programming tasks si

multaneously The central notion is that of generic algorithms which are parameterized

pro cedural schemata that are completely indep endent of the underlying data representa

tion and are derived from concrete ecient algorithms The purp ose of this pap er is to

convey the key ideas of generic programming fo cusing mainly on establishing a metho

ological framework that includes appropriate notions of algorithm and data abstractions

and what it means to formally sp ecify and verify such abstractions

We present the issues relating to generic algorithms mainly in terms of a single ex

ample a Partition algorithm such as is used in quicksort but we will also allude to

a large collection of examples wehavedevelop ed in Ada as part of an Ada Generic Li

brary pro ject The structure of the library is designed to achievea much higher

degree of mo dularity than has b een found in previous libraries by completely separating

data representations from algorithmic and other data abstraction issues Some of our

goals are in common with the parameterized programming approachadvo cated byJ

Goguen but the most fundamental dierence is that Goguen mainly addresses meta

issuesnamelyhow to manipulate theorieswhile our primary interest is in building

useful theories to manipulate

The notion of generic algorithms is not new but we are unaware of any similar attempt

to structure a software library founded on this idea The Ada library develop ed byG

Booch for example makes only very limited use of generic algorithms Boochhas

develop ed an interesting taxonomy of data structures and has p opulated it with many

dierent abstract data typ es but the implementations of these data typ es are for the most

part built directly on Adas own facilities rather than using other data

abstractions in the library ie there is very little layering of the implementations Some

use of generic algorithms and layering is describ ed for list and tree structure algorithms

but almost as an afterthoughtinachapter on utilities

In fact most work on development of abstraction facilities for the past decade or

more has fo cused on data abstraction Algorithmic abstraction has received little

attention even in the more recentwork on ob ject oriented programming Most work on

pro cedural abstraction has b een language rather than algorithmoriented attempting to

nd elegant and concise linguistic primitives our goal is to nd abstract representations

of ecient algorithms

As an example of algorithmic abstraction consider the task of cho osing and imple

menting a sorting algorithm for data structures The merge algorithm

CLASSIFICATION OF ABSTRACTIONS

can b e used and if prop erly implemented provides one of the most ecient sorting al

gorithms for linked lists Ordinarily one might program this algorithm directly in terms

of whatever p ointer and record eld access op erations are provided in the programming

language Instead however one can abstract away a concrete representation and express

the algorithm in terms of the smallest p ossible numb er of generic op erations In this case

we essentially need just four op erations Next and Next for accessing the next cell in

End for detecting the end of a list and Test a binary predicate on the data in a list Is

cells For a particular representation of linked lists one then obtains the corresp onding

version of a merge sorting algorithm by instantiating the generic access op erations to b e

subprograms that access that representation

We b elieve it is b etter whenever p ossible to give programming examples in a real

language rather than using pseudolanguage as is so frequently done Although wedonot

argue that Ada is p erfect for expressing the programming abstractions wehave found most

useful it has b een adequate in most cases and it supp orts our goal of eciency through

its compile time expansion of generics and provision for directing that subprograms b e

compiled inline For numerous examples of the use of generic programming techniques in

the Scheme language and a brief discussion of the relative merits of Ada and Scheme for

this typ e of programming see

Classication of Abstractions

We discuss four classes of abstractions that wehave found useful in generic programming

as shown in Table which lists a few examples of packages in our Ada Generic library

Each of these Ada packages has b een written to provide generic algorithms and generic

data structures that fall into the corresp onding abstraction class

Data abstractions

Data abstractions are data typ es and sets of op erations dened on them the usual deni

tion they are abstractions mainly in that they can b e understo o d and formally sp ecied

by such techniques as algebraic axioms indep endently of their actual implementation In

Ada data abstractions can b e written as packages which dene a new typ e and pro ce

dures and functions on that typ e Another degree of abstractness is achieved by using a

generic packageinwhichthetyp e of elements b eing stored is a generic formal parameter

In our librarywe program only a few such data abstractions directlythose necessary

to create some fundamental data representations and dene how they are implemented

Algorithmic abstractions

Data Abstractions System Allo cated Singly Linked

Data typ es with op erations User Allo cated Singly Linked

dened on them fInstantiations of representational abstractionsg

Algorithmic Abstractions Sequence Algorithms

Families of data abstractions Linked List Algorithms

with common algorithms Vector Algorithms

Structural Abstractions Singly Linked Lists

Intersections of Doubly Linked Lists

algorithmic abstractions Vectors

Representational Abstractions Double Ended Lists

Mappings from one structural Stacks

abstraction to another Output Restricted Deques

Table Classication of Abstractions and Example Ada Packages

in terms of Ada typ es suchasarrays records and access typ es Most other data abstrac

tions are obtained bycombining existing data abstraction packages with packages from

the structural or representational classes dened b elow

Algorithmic abstractions

These are families of data abstractions that have a set of ecient algorithms in common

we refer to the algorithms themselves as generic algorithms For example in our Ada

library there is a package of generic algorithms for linkedlists and a more general package

of sequence algorithms whose memb ers can b e used on either linkedlist or vector repre

sentations of sequences The linkedlist generic algorithms package contains dierent

algorithms such as for example generic merge and sort algorithms that are instantiated

in various ways to pro duce merge and sort subprograms in structural abstraction packages

such as singlylinked lists and doublylinked lists We stress that the algorithms at this

level are derived by abstraction from concrete ecient algorithms

Structural abstractions

Structural abstractions with resp ect to a given set of algorithmic abstractions are also

families of data abstractions a data abstraction A b elongs to a structural abstraction

ALGORITHMIC ABSTRACTIONS

S if and only if S is an intersection of some of the algorithmic abstractions to which

A b elongs An example is singlylinkedlists the intersection of sequence linkedlist

and singlylinkedlistalgorithmic abstractions It is a family of all data abstractions that

implement a singlylinked representation of sequences it is this connection with more

detailed structure of representations that inspires the name structural abstraction

Note that as an intersection of algorithmic abstractions such a family of data ab

stractions is smaller than the algorithm abstraction classes in whichitiscontained but

a larger numb er of algorithms are p ossible b ecause the structure on which they op erate

is more completely dened

Programming of structural abstractions can b e accomplished in Ada with the same

Linked Lists of generic package structure as for generic algorithms The Singly

package contains subprograms most of which are obtained by instantiating or calling

Algorithms package or one of the linked in various ways some member of the Sequence

list algorithms packages In Ada to place one data abstraction in the singlylinkedlists

family one instantiates the Singly Linked Lists package using as actual parameters

atyp e and the set of op erations on this typ e from a data abstraction package suchas

System Allocated Singly Linked that denes an appropriate representation

Representational abstractions

These are mappings from one structural abstraction to another creating a new typ e

and implementing a set of op erations on that typ e by means of the op erations of the

domain structural abstraction For example stacks can easily b e obtained as a structural

abstraction from singlylinkedlists Note that what one obtains is really a family of stack

data abstractions whereas the usual programming techniques give only a single data

abstraction

The following sections give more detailed examples of algorithmic abstractions Fur

ther discussion and examples of data structural and representational abstraction may

b e found in

Algorithmic Abstractions

As an example of generic algorithms we consider the sequence algorithmic abstraction

diverse data abstractions which can b e sequentially traversed These data abstractions

b elong to numerous dierent families singlylinked lists doublylinked lists vectors trees

and many others There are many algorithms that make sense on all of them and require

only a few simple access op erations for their implementation nd an element accumulate

values together by or for example countelements satisfying some predicate etc

The solution that has b een taken in is to index all kinds of sequences

by natural numb ers So the Common Lisp generic find function always returns a natural

numb er which is not particularly useful on linked lists

In the generic programming approach we use generic indexing by a generic formal

typ e Coordinate Coordinate is instantiated to typ e Natural for vectors for linked

lists however cells themselves can serveas Coordinate values A generic Find can thus

return a Coordinate value that can b e used to reference the lo cated element directly

The intended semantics for Coordinate is that there are functions

Initial from Sequence to Coordinate

Next from Coordinate to Coordinate

End from Sequence Coordinate to Booleanand Is

Ref from Sequence Coordinate to a third typ e Element

such that for any sequence S there are a natural number N called the length of S and

co ordinates I I I such that

 N

I InitialS and I NextI for i N

i i

the elements of S are given by RefS I RefS I RefS I

 N 

Is EndS I isfalsefor i N and true for i N

i

End is a constant We further assume that each of the functions Initial Next Refand Is

time op eration It is imp ortantthat Ref provides constant time access so that after Find

returns the co ordinate it is p ossible to access the data without any additional traversal of

the sequence Thus for example one could not use natural numb ers as co ordinates when

the sequences are linked lists

In Ada we can write

generic

type Sequence is private

type Coordinate is private

type Element is private

with function InitialS Sequence return Coordinate

ALGORITHMIC ABSTRACTIONS

with function Next Coordinate return Coordinate

with function IsEndS Sequence C Coordinate return Boolean

with function RefS Sequence C Coordinate return Element

package SequenceAlgorithms is

definitions of sequence algorithms such as

Count Find Every Notany Some Search eg

generic

with function TestS Sequence C Coordinate return Boolean

procedure FindS Sequence

Result out Coordinate

IsFound out Boolean

end SequenceAlgorithms

Wehave made Find a pro cedure instead of a function so that the case in whichan

element satisfying Test is not found do es not require some extra co ordinate value to b e

returned such an extra value might not exist for some instances of the co ordinate typ e

Note also that Find is a generic pro cedure in addition to forming an instance of the

Sequence Algorithms package the programmer would also create particular instances

of Find in which some particular test such as equality to a particular value would b e

substituted for Test

The b o dy of Find could b e expressed as follows

package body SequenceAlgorithms is

among other things

procedure FindS Sequence

Result out Coordinate

IsFound out Boolean is

Current Coordinate

Flag Boolean

begin

Current InitialS

while not IsEndS Current loop

if TestS Current then

Result Current IsFound True return

end if

Current NextCurrent

end loop Result Current IsFound False

end Find

end SequenceAlgorithms

It should b e noted that not every p ossible data abstraction whichcontains a set of elements

can b e a memb er of the sequence algorithmic abstraction Some data abstractions do not

contain an explicit co ordinate typ e stacks or queues for example Intuitively sp eaking

the intended data abstractions are those which can b e iterated through without side

eects and where there is a co ordinate typ e which can b e used to represent the current

p osition in a manner allowing constant time access

A Generic Partition Algorithm

Another limitation of sequence algorithms as wehave dened them in the previous section

is that they allow only for onedirectional traversals of sequences There are several

algorithms which require a bidirectional traversal of sequences bytwovariables of the

typ e Coordinate advancing towards each other If we assume there is a Prev op eration

such that PrevNextI NextPrevI I and a Swap op eration for exchanging

elements then we can obtain generic implementations of such pro cedures as Reverse and

Partition as in quicksort We examine the Partition algorithm in particular as a

more detailed example of the issues that arise with programming and reasoning ab out

algorithmic abstractions

In Ada we could pro vide such algorithms in a generic package

generic

type Sequence is private

type Coordinate is private

with function NextI Coordinate return Coordinate

with function PrevI Coordinate return Coordinate

with procedure SwapS in out Sequence I J Coordinate

package BidirectionalSequenceAlgorithms is

for example

procedure ReverseS in out Sequence

generic

with function TestS Sequence C Coordinate return Boolean

procedure PartitionS in out Sequence

ABSTRACT ALGORITHM SPECIFICATION AND VERIFICATION

F L in Coordinate

Middle out Coordinate

MiddleOK out Boolean

end BidirectionalSequenceAlgorithms

which could b e used along with the Sequence Algorithms package to construct collections

of algorithms for dierent kinds of linear lists In this package we do not need to have

Element and Ref as generic parameters since algorithms suchas Reverse and Partition

do not directly refer to them

To describ e the Partition algorithm informally a formal treatment follows in Sec

tion we sp eak of NextI giving a larger co ordinate than I and Prev giving one

that is smaller and we also sp eak of elements that satisfy Test as go o d and those that

dont as bad Provided SwapS I J exchanges the elements with co ordinates I and

J and leaves all other elements of S unchanged the Partition algorithm rearranges the

elements of S between those with co ordinates F and L so that all of the go o d elements

come rst followed by all the bad elements Middle M is computed as a co ordinate

between F and L inclusive such that all of the elements with smaller co ordinates are

go o d and all elements with greater co ordinates are bad the M th element is good if and

Middle OK is true only if

Middle OK is needed b ecause for N elements there are N p ossibilities for the

b oundary b etween go o d and bad elements but we are guaranteed of having only N

co ordinate values in general we cannot assume the existence of co ordinate values outside

the range from F to L This complication do es not arise with the usual concrete partition

algorithm in which co ordinates are integers since one could use values F orL for

M This is an example of the extra care that must b e taken in expressing an algorithm

at a more abstract level

The Partition algorithm can b e expressed in Ada as shown in Figure A somewhat

shorter implementation could b e achieved in which calls to Test with the same arguments

might b e rep eated but since Test is a generic parameter wemust b e careful to avoid

such redundant calls since one might instantiate the algorithm with a Test that is fairly

exp ensive to compute

Abstract Algorithm Sp ecication and Verication

The main idea of our approach to sp ecication and verication of a generic algorithm is

similar to classical program verication techniques eg Dijkstras idea of weakest pre

procedure PartitionS in out Sequence

F L in Coordinate

Middle out Coordinate

MiddleOK out Boolean is

First Coordinate F

Last Coordinate L

begin

loop

loop

if First Last then

Middle First

MiddleOK TestS First

return

end if

exit when not TestS First

First NextFirst

end loop

loop

exit when TestS Last

Last PrevLast

if First Last then

Middle First

MiddleOK False

return

end if

end loop

SwapS First Last

First NextFirst

if First Last then

Middle First

MiddleOK False

return

end if

Last PrevLast

end loop

end Partition

Figure Bo dy of Partition Algorithm

ABSTRACT ALGORITHM SPECIFICATION AND VERIFICATION

conditions in which one attempts to obtain a strong statement ab out the result of a

computation while making as few assumptions as p ossible ab out its initial conditions In

discussing preconditions of ordinary nongeneric algorithms the assumptions one makes

ab out the op erations in terms of which the algorithm is expressed are xed since the

op erations themselves are xed But for generic algorithms wewanttomake these op

erations generic parameters and vary the assumptions ab out them our goal is b oth to

consider a variety of p ossible p ostconditions and to maximize the numb er of dierent

mo dels abstract data typ es under which an an algorithm attains a given p ostcondition

In terms of pro of theorywewant to consider how to provevarious p ostconditions under

avariety of assumptions ab out the generic parameters so that later we can easily prove

correctness of a wide variety of instances

It app ears that the b est approach is to build up the sp ecications and the verication

lemmas in stages just as we build up algorithmic capabilities in layers In fact we will

nd it advantageous to haveeven more layering in the sp ecications and pro ofs than in

the construction of the algorithms

Weintro duce the main ideas in terms of the Partition algorithm given in the previous

section What are the minimal assumptions weneedtomake ab out the generic parameters

in terms of which Partition is programmed namely the Sequence and Coordinate

typ es and the Next Prev and Swap op erations If wewant to use the algorithm only

for partitioning in the usual sense and the only use of abstraction is in the use of the

Coordinate typ e rather than a more sp ecic in teger typ e for an arrayversion or p ointer

typ e for a linked list version then we could carry out the sp ecication and pro of in one

step in whichwe make strong assumptions ab out the generic parameters

Instead however we b egin with weaker assumptions ab out these generic parameters

and obtain a lemma ab out the results of Partition that enables us to deal with less

conventional instances of partitioning For example supp ose that we are only interested

in the part of the output consisting of elements that satisfy Test ie we do not need to

pro cess the elements that dont satisfy it Then we can obtain a more ecient partitioning

algorithm by using for SwapS I J an op eration that just p erforms the assignmentof

the element with the J th co ordinate to the I th co ordinate If we had made a stronger

assumption ab out Swap that it exchanges twoelements in the sequence then the theorem

ab out the generic algorithm would not b e applicable to this instance

Instead we carry out the sp ecication and pro ofs in layers one of which allows us

to tap in at the level weneedtoverify the second kind of Partition while the rst

more usual kind can b e veried when additional assumptions are made ab out Swap and

combined with the lemma stated at the rst level

First we assume that asso ciated with the Coordinate typ e there is a predicate

Basic sp ecication of Partition



whichisawellfounded partial ordering on Coordinate dened by

N

IJN N and J Next I

For co ordinates F and L where F Lwe dene

i

Coordinate RangeF LfNext F i N g

N

where N is the smallest integer suchthat Next F L Note that

i N i

Prev LNext F

Basic sp ecication of Partition

Initially wemake only a weak assumption ab out Swap

RangeF L then SwapS I J com Swap Assumption If I J Coordinate

putes S such that for all K Coordinate RangeF L fI J g



TestS KTestS K



The reason that wecangetby with suchaweak assumption is simply that we express the

result Partition computes as equivalent to that pro duced by a straightline sequence of

calls of Swap The sp ecication asserts the existence of two sequences of co ordinate values

that serve as arguments to the Swap calls and constrains the relationship b etween these

values

Syntactic Sp ecication

procedure PartitionS in out Sequence

F L in Coordinate

Middle out Coordinate

MiddleOK out Boolean

Formal Semantics

Next and Prev are assumed to ob ey the relations discussed ab ove and to haveno

side eects Swap is assumed to ob ey Swap Assumption With inputs S S F

F L L with F L according to the partial ordering relation dened ab ove

Partition outputs S S Middle M Middle OK B such that



Note that is not generic parameter of the package b ecause it is not used in expressing the algorithms

themselves as it would b e exp ensive to implementforsay doublylinked lists

ABSTRACT ALGORITHM SPECIFICATION AND VERIFICATION

M Coordinate RangeF L

There are two sets of co ordinates

Coordinate RangeF M if B is true

Accept

RangeF M fM g if B is false Coordinate

Reject Coordinate RangeF L Accept

and a nonnegativeinteger n and two Coordinate sequences I I and

 n

J J suchthat

 n

a F I I M J J L

 n n 

b For k n TestS I is false while TestS J is true

k k

c For P Accept fI I g TestS P is true

 n

d For P Reject fJ J g TestS P is false

 n

e S is the nal value of S computed by



SwapS I J SwapS I J

  n n

The fact that the co ordinate typ e is abstract comp els taking considerable care in this

sp ecication to avoid the mention of co ordinate values that might not exist eg we write

RangeF M fM g instead of Coordinate RangeF PrevM Coordinate

Later weshowhow the ab ove inputoutput sp ecication can b e proved as a lemma by

annotating the algorithm with assertions and using the inductive assertions metho d For

now we consider howtocombine this sp ecication with additional assumptions ab out

Swap in order to draw stronger conclusions ab out the output of PartitionWe add these

assumptions one at a time thereby obtaining several useful lemmas that apply to dierent

instances of Partition

Obtaining a sequence satisfying Test

By making a second assumption ab out Swapwe can draw a stronger conclusion ab out

Partition

RangeF L then SwapS I J com Swap Assumption If I J Coordinate

putes S such that



TestS I TestS J



This can b e combined with the basic Partition sp ecication to deduce

Obtaining a sequence satisfying Test

Partition Lemma If Swap satises Swap Assumptions and then the sequence S



computedby Partition satises

Partition Prop erty For al l K Accept TestS K is true



Similarlywe can intro duce

Swap Assumption If I J Coordinate RangeF L then SwapS I J com

putes S such that



TestS J TestS I



and this can b e combined with the basic Partition sp ecication to deduce

Partition Lemma If Swap satises Swap Assumptions and then the sequence S



computedby Partition satises

Partition Prop erty For al l K Reject TestS K is false



Partition Lemma If Swap satises Swap Assumptions and then the sequence

S computedby Partition satises Partition Properties and



Notethatwehavenotyet made any assumption ab out Swap actually exchanging

two elements of a sequence wehave only assumed that it do es not aect elements other

than those with co ordinates I and J insofar as can b e determined by Test and that it

hanges the I th elementtohave the same Testvalue as the J th or viceversa Thus c

for example if wehave sequences of integers and Test just checks whether an elementis

p ositive a Swap op eration that assigns or totheI th element according to whether

the J th is nonp ositive or p ositivewould satisfy Swap Assumption and

Thus to b e able to conclude that the sequence S computed by Partition is a p er



mutation of its input S we need to assume that Swap satises

Swap Assumption If I J Coordinate RangeF L then SwapS I J com

RangeF L fI J g putes S such that for all K Coordinate



RefS KRefS K



Swap Assumption If I J Coordinate RangeF L then SwapS I J com

putes S such that RefS IRefS J

 

ABSTRACT ALGORITHM SPECIFICATION AND VERIFICATION

Swap Assumption If I J Coordinate RangeF L then SwapS I J com

putes S such that RefS J RefS I

 

From these assumptions we obtain

Partition Lemma If Swap satises Swap Assumptions and then it also satis

es Swap Assumptions and and Partition has Partition Properties and as

wel l as

Partition Prop erty The output sequence S is a permutation of the input sequence



S

Correctness when Swap is an assignment op eration

Now supp ose instead of p erforming an exchangeoftwoelements Swap just do es an

assignment op eration so that it satises Swap Assumption but not Swap Assumption

We can still conclude

Partition Lemma If Swap satises Swap Assumptions and then it also satises

Swap Assumptions and and Partition has Partition Property as wel l as

Partition Prop erty The sequence of elements of the output sequence S with co



ordinates in Accept is the subsequence of the elements of S with coor dinates in

RangeF L and satisfying Test Coordinate

This tells us that by instantiating Partition with Swap as an assignment op eration we

obtain a version that brings together all the elements that satisfy Test It do es not yield

all the elements that do not satisfy Test but in some applications wewould not need this

information

The main b enet of dividing the sp ecication of assumptions ab out Swap and con

clusions ab out Partition into small pieces is that we can deal with the question of

correctness of dierent instances merely by citing the appropriate lemmas or we can

create and prove new lemmas with comparatively little eort The work of pro of has

b een factored into small steps that allow us the same b enets of reuse in pro ofs as generic

algorithms allow us in programming

Correctness of the b o dy of Partition

Correctness of the b o dy of Partition

To prove partial correctness we add three internal assertions to the b o dy of Partition

Figure In these assertions note that S refers to the initial value of variable S while

S refers to the currentvalue at the p oint of the assertion



At the b eginning of the rst inner lo op There are a nonnegativeinteger n and

two Coordinate sequences I I and J J suchthat

 n  n

a F I I First Last J J L

 n n 

b For k n TestS I is false while TestS J istrue

k k

c for P Coordinate RangeF First fI I Firstg TestS P is true

 n

RangeLastL fLastJ J g TestS P is false d for P Coordinate

 n

e The currentvalue S of S is the value of S computed by



SwapS I J SwapS I J

  n n

At the b eginning of the second inner lo op Assertion First Lastand

TestS First is false

Just b efore the Swap call Assertion and TestS Last is true

These assertions along with entry and exit assertions obtained from the Formal Semantics

of the algorithm are sucient for carrying out an inductive assertions pro of of partial

correctness any path from the b eginning of the pro cedure to the exit is comp osed of a

nite numb er of path segments b etween two assertions and one can verify that for each

such path segment the assertion at the b eginning combined with the semantics of the

statements along the path implies the assertion at the end We omit these pro ofs

Toprove total correctness we need to show also that the pro cedure always terminates

Actually the result weprove is conditional on the termination of Test and Swap Note

that

it can b e shown inductively that at all times First Last

every path segment as dened in the partial correctness pro of that can b e rep eated

in any execution of the pro cedure contains an assignment that increases First or

decreases Last on one path b oth are changed but not without violating

REFERENCES

Therefore any execution consists of only a nite numb er of path segments Since each

path segmentcontains only assignment statements equality tests or calls to Test and

Swapwehave

Partition Lemma If the generic parameters Test and Swap always terminate then

Partition always terminates

Conclusion

In this pap er wehave attempted to develop a framework sucient to encompass the key

asp ects of generic programming with illustrations from our exp erience in building a li

brary of generic software comp onents in Ada Although the do cumentation of the initial

library in is informal and wehavenotyet carried out formal sp ecication and veri

cation of the library comp onents we b elieve that this task would b e b oth mathematically

very interesting and practically very useful

On the mathematical side the correctness of generic algorithms oers greater chal

lenges and less tedium than concrete algorithms for often one must create the appropriate

abstract concepts in terms of which one can eectively express and reason ab out the b e

havior of an algorithm or collection of algorithms The nature of the problem of verifying

generic algorithms should b e attractive to researchers in computer science and mathemat

ics whereas the problem for concrete algorithms is often regarded as so tedious as to b e

worth doing only if most of the work can b e done with an automated reasoning system

On the practical side the considerable work of comp osing a formal sp ecication and

carrying out a detailed pro of of correctness at a generic level is comp ensated by the ease

with which one is then able to deal with the correctness of many distinct instantiations

While it is often dicult to justify the amount of eort required for formal verication

of concrete programs except in the case of software used in lifecritical systems the

p ossibilityofverifying comp onents in generic softw are libraries mayopentheway for the

b enets of this technology to b ecome much more widely available

References

G Bo o ch Software Comp onents in Ada BenjaminCummings

OJ Dahl E W Dijkstra and C A R Hoare Academic Press

REFERENCES

E W Dijkstra A Discipline of Programming PrenticeHall Englewo o d Clis New

Jersey

J Goguen Parameterized Programming Transactions on Software Engineering

SE Septemb er

A Kershenbaum D R Musser and A A Stepanov Higher Order Imp erative Pro

gramming Computer Science Dept Rep No Rensselaer Polytechnic Insti

tute Troy New York April

D R Musser and A A Stepanov A Library of Generic Algorithms in Ada Pro c

of ACM SIGAda International Conference Boston Decemb er

D R Musser and A A Stepanov The Ada Generic Library Linear List Pro cessing

Packages SpringerVerlag This b o ok sup ercedes General Electric Corp orate

Research and Development Rep orts CRD and CRD April

G L Steele Common LISP The Language Digital Press

N Wirth Algorithms Data Structures Programs PrenticeHall