brl mr 3?ba brl · 2011-05-15 · brl mr 3?ba memorandum report brl-mr-3784 brl n! program...

24
BRL MR3?bA MEMORANDUM REPORT BRL-MR-3784 BRL N! PROGRAM TRANSFORMATION cv) WITH ABSTRACT RELATION ALGEBRAS N PAUL BROOME T OCTOBER 1989 U--- APPROVED FOR PUBLIC REIEASE DISTRIBUTION UNLIMr"ED U.S. ARMY LABORATORY COMMAND BALLISTIC RESEARCH LABORATORY ABERDEEN PROVING GROUND, MARYLAND i i i1 I I I I I

Upload: others

Post on 03-Mar-2020

15 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: BRL MR 3?bA BRL · 2011-05-15 · brl mr 3?ba memorandum report brl-mr-3784 brl n! program transformation cv) with abstract relation algebras n paul broome t october 1989 u--- approved

BRL MR 3?bA

MEMORANDUM REPORT BRL-MR-3784

BRLN! PROGRAM TRANSFORMATION

cv) WITH ABSTRACT RELATION ALGEBRAS

N

PAUL BROOME T

OCTOBER 1989 U---

APPROVED FOR PUBLIC REIEASE DISTRIBUTION UNLIMr"ED

U.S. ARMY LABORATORY COMMAND

BALLISTIC RESEARCH LABORATORYABERDEEN PROVING GROUND, MARYLAND

i i i1 I I I I I

Page 2: BRL MR 3?bA BRL · 2011-05-15 · brl mr 3?ba memorandum report brl-mr-3784 brl n! program transformation cv) with abstract relation algebras n paul broome t october 1989 u--- approved

DESTRUCTION NOTICE

Dcstro this report when it is no longer needed. DO NOT return it to the originator.

Additional copies of this report may be obtained from the National Technical Information Service, U.S.Department of Commerce, Springfield, VA 22161.

The findings of this report are not to be construed as an official Department of the Army position,unless so designated by other authorized documents.

The use of trade names or manufacturers' names in this report does not constitute indorsement of anycommerical product.

LNc1.S.TSMD LNLDr1MD

Page 3: BRL MR 3?bA BRL · 2011-05-15 · brl mr 3?ba memorandum report brl-mr-3784 brl n! program transformation cv) with abstract relation algebras n paul broome t october 1989 u--- approved

UNCLASSIFIEDSECURITY CLASSIFICATION OF TH!S PAGE

Form Approved

REPORT DOCUMENTATION PAGE OMBNo 070Oe

la REPORT SECUR:TY CLAS ,F;CATiON lb RESTRICTIVE MARKINGS

2a SECURITY CLASSIFICATION AUTHORITY 3 DISTRIBUTION /AVAILABILITY OF REPORT

2b DECLASSIFICATION / DOWNGRADING SCHEDULE Distribution Urliited

4 PERFORMING ORGANIZATION REPORT NUMBER(S) 5 MONITORING ORGANIZATION REPORT NUMBER(S)

BRL-MR- 3784

6a NAME OF P RFORM.NG ORGANIZATION 6 OFFICE SYMBOL 7a NAME OF MONITORING ORGANIZATIONSyste Engineering & Concepts (if applicable)

Analysis Division ISLICBR-SE-C US Army Ballistic Research Laboratory

6c ADDRESS (City, State, and ZIP Code) 7b ADDRESS (City, State. and ZIP Code)

USA Ballistic Research Laboratory ATTN: SLCBR-DAberdeen Proving Ground, MD 21005-5066 Aberdeen Proving Ground, M 21005-50G

Ba NAME OF FUNDING, SPONSORING 8b OFFICE SYMBOL 9 PROCUREMENT INSTRUMENT IDENTIFICATION NUMBERORGANIZATiON (If applicable)

8c. ADDRESS (City, State, and ZIP Code) 10 SOURCE OF FUNDING NUMBERS

PROGRAM PROJECT TASK WORK UNTELEMENT NO NO NO ACCESSION NO

11 TITLE (Include Security Classification)

PIRGRAM TRIMISFOR.ATION WITH ABSTRACT RELATION ALERAS

12 PERSONAL AUTHOR(S)PAULT H4. BRFn-)ME

,3a. TYPE OF REPOPT 13b TIME COVERED 14 DATE OF REPORT (Year, Month, Day) 1S PAGE COUNTSMemra , FROM TO

16. SUPPLEMENTARY NOTATION

17 COSATI CODES 18 SUBJECT TERMS (Continue on reverse if necessary ard identify by block number)

FIELD GROUP SUB-GROuP Program Transformation; Relation Algebra; Logic Programrming;

'Functional Programming.

19 ABSTRACT (Continue on reverse if necessary and ide-ntify by block number)

Our objective is to satisfy two seeningly opposing constraints on program design. We want

to begin a program as an obvious formal specification but also insist upon efficientexecution.

Our approach is to find ex-ressive, model independent program constructs with algebraicproperties that can show logical equivalence between a clear specification and an efficientprogram.

Our solution is an implementation of scme of the relations, relation operators, and equationsthat cmprise Tarski's Q-relation algebra. The key to this solution is a single operatorfor linear recursions that satisfies two equations. The first merges recursions and thesecond propagates constraints for early pruning of the rnproductive branches of theoa putation tree.

20 DISTRIBUTION/AVAILABILITY OF ABSTRACT 21 ABSTRACT SECURITY CLASSIFICATION

0 UNCLASSIFIED/UNLIMITED E0 SAME AS RPT C DTIC USERS NCLASSIFIED22a. NAOJ

'c OF RESPONSIBLE INDIVIDUAL 22b TELEPHONE (froclude Area Code) 22c LOFFICE SYMBOL

PAUL H. RC)NE 31-278-L . .I _ :-.AE-

DD Form 1473, JUN 86 Previous editions are obsolete. SECUR,TY CLASSIFICATION OF THIS PAGE

UNCLASSIFIED

Page 4: BRL MR 3?bA BRL · 2011-05-15 · brl mr 3?ba memorandum report brl-mr-3784 brl n! program transformation cv) with abstract relation algebras n paul broome t october 1989 u--- approved

iii

Contents

1 Introduction 1

2 Motivation 1

3 Preliminaries 2

4 Application to programs 64.1 Diversity and Complement .......................... . . 74.2 Sequence construction and selection ...... ................... 8

5 Linear recursion 8

6 Transformations 116.1 Disjointedness as empty intersection ...... ................... 126.2 Eliminating intermediate lists ....... ....................... 13

7 Conclusion 14

Accession For

NTIS GRA&I[

DTI7 TAB 0J

Distri bution/

Availability CodesAvail and/or

Dist Special

Page 5: BRL MR 3?bA BRL · 2011-05-15 · brl mr 3?ba memorandum report brl-mr-3784 brl n! program transformation cv) with abstract relation algebras n paul broome t october 1989 u--- approved

1 Introduction

One of the most attractive program development methods is transformational pro-gramming. In this report we explore transformation oriented language design. Westart with the assumptions that

1. Programs are to be initially written as straightforward, understandable, exe-cutable specifications. More efficient, but probably less readable, programs arederived through correctness preserving transformations.

2. Functional and relational operators provide an appropriate context for specifi-cations. They have the algebraic properties required for the transformations.

The central contribution is the application of Tarski's RA and Q-relation algebras[1] to program transformation. We find the notation is a convenient combination oflogic programming and functional programming. This middle ground has the express-ibility of the former and the manipulability of the latter because it provides for higherorder operations in a first order way. A key contribution is a single operator for linearrecursions over regularly structured objects along with equations for merging loopsand propagating constraints.

2 Motivation

Operators have been largely ignored in logic programming languages. In general thegreater the amount of pattern directed invocation of procedures there is in a language,the less the dependence on operators. This need not and should not be the case asboth concepts are an important part of modern programming languages, and operatorshelp reason about programs at a high level.

An operator in Prolog is a program clause, describing an n-ary relation, with avariable that is called as a predicate in the body of the clause. Warren [2] describedhow to define higher order operators in Prolog and argued that extending the Prologlanguage definition to include them was, in large part, unnecessary. Indeed, theirdefinitions are simple but they are awkward to use.

For example, the following Prolog program defines a 4 argument relation iterateand exhibits the difficulties with higher order operators in Prolog. The first argumentof iterate is a sequence and the second, F, is a predicate of 3 arguments. The thirdargument, Z, is normally a right identity for F although this is not required. It isthe answer supplied when iterated over an empty list. Finally, the last argument foriterate is the result.

Page 6: BRL MR 3?bA BRL · 2011-05-15 · brl mr 3?ba memorandum report brl-mr-3784 brl n! program transformation cv) with abstract relation algebras n paul broome t october 1989 u--- approved

2

EXAMPLE I A Prolog iterate operator

iterate([ ], F,Z,Z).iterate([XIL], F, Z,) -

iterate(L, F, Z, YO),

F(X, Yo, Y).

Operators defined this way are not often directly applicable as thert is no con-vention about the number of arguments in a predicate. In particular, iterate expectSa function, such as plus, with exactly three arguments such that the first two aredifferent 'inputs' and the third is an answer. Secondly, lists are 'wired into' the firstargument. For example, it cannot be used to generate the first N integers such aswith APL's iota. Finally, this operator does not describe all iterations over lists. Anexample is map which applies the same function in a one-to--one fashion to each itemof a list. Each of these linear recursions requires a new definition and a combinatorialincrease in the effort to reason about their combinations.

If a program construct is to be manipulated then it must satisfy some algebraicproperties. These properties are most applicable if the construct is abstractly defined,independently of a model. The following preliminaries are model independent.

3 Preliminaries

We will interpret the notation as both mathematical symbols and as program con-structs but recognize that the two are distinct. Within definitions and argumentsfor correctness we follow Tarski's extended predicate logic £+ [1]. Propositions arestatements of the algebraic properties of relation operators. However, definitions arealso interpreted as program clauses and propositions as properties of program formingoperations. We view every program as a relation between inputs and outputs withthe proviso that the viewpoint can be reversed, when feasible, to construct inputsfrom outputs. These transformations reduce the size of the computation tree and areapplicable to both sequential and OR-parallel computations if conjuctions of subgoalsare solved from left to right.

The algebraic terminology categorizes a portion of the large collection of relationequations. It also helps describe algorithms abstractly, independently of a model Themost specific structures are relation algebras and Q-relation algebras as described in[1]. Table I is a summary of notation.

Page 7: BRL MR 3?bA BRL · 2011-05-15 · brl mr 3?ba memorandum report brl-mr-3784 brl n! program transformation cv) with abstract relation algebras n paul broome t october 1989 u--- approved

3

Symbol MeaningA - Z variables

a - z constants or function symbols7 set of terms

S set of ground terms

r(S) set of binary relations on S

A logical andV logical or- logical negation

3 existential quantifier

V universal quantifier

- if and only if

is provable if

= defined or proved equivalent to

[-I-] ordered couple

Table 1: Summary of notation

The theory of relations is one of the most developed branches of logic[1,3,4]. Inparticular. the calculus of binary relations follows the well understood laws of Booleanalgebra.

A Boolean algebra is a structure (U, U,-). Although there are no implicit assump-tions about the underlying universe U, we are most interested in algebras defined onB(S). The following is an sample axiomatization.

(X UY) UZ = X U (Y U Z), (1)

XUY=YUX, (2)

X = (X UY) UXu Y (3)

A relation algebra is a structure (u, u,-, o,', id). The common language describesthese operations as union, complementation, composition, converse, and the iden-tity. A summary of the relation operators appears in Table 2. The following is anaxiomatization for RA [1,5].

(FuG) U H FU(GU H), (4)

FuG=GUF, (5)

F E (F UG) U(FUG), (6)

Page 8: BRL MR 3?bA BRL · 2011-05-15 · brl mr 3?ba memorandum report brl-mr-3784 brl n! program transformation cv) with abstract relation algebras n paul broome t october 1989 u--- approved

4

Relation Symbol Meaningempty relation

w universal relationR U S union of relations

R f S intersection of relationsRCS ordered coupler of relations

R o S relative product or composition

R complement of the relation R

R converse of a relation

R' monoid closure of R

[RIS3 relational constructor of couples7r(D, S, C) linear recursion

id identity relation

di diversity relation

hd first conjugated projectiontl second conjugated projection

Table 2: Summary of Relations and Relation Operators

F o (Go H) = (FoG)o H, (7)(F UG) oH E FoHUGo H, (8)

F o id = F, (9)

F- F, (10)

(F UG)- F-UG-, (11)(F oG) - = G- o F', (12)

FoFoGUG = G. (13)

From these fundamental operations we can abstractly define other relations andrelation operators. Positive, logical definitions of intersection F n G and the universalrelation w are preferred. They are more easily implemented and constructive proofsare more intuitive. Implementation considerations for negations such as complementand diversity di are discussed in the next section.

F-nG =- FUG, (14)w -iduid, (15)

-- i, (16)

Page 9: BRL MR 3?bA BRL · 2011-05-15 · brl mr 3?ba memorandum report brl-mr-3784 brl n! program transformation cv) with abstract relation algebras n paul broome t october 1989 u--- approved

5

di =_ d. (17)

It is easy, but tedious, to check that the following logical definitions for these relationoperators satisfy the properties of an RA.

VXY{X (FnG) Y - X F Y A X G Y), (18)VXY{X (FUG))Y-X FYVX G Y), (19)

VXY{X (FoG) Y -- B{ZX F Z AZ G Y)}, (20)

VXY{X F Y - Y F X}, (21)

VX{X id X), (22)

VxY{x W Y}, (23)VX Y{X T Y - .. (X F Y}, (24)

VXY{X di Y - -(X id Y). (25)

Other simple properties of union and intersection follow.

A U -A. (26)

SU A -A, (27)(An B) n C = A n(B n C), (28)

A n, E_ A, (29)w n A _ A. (30)

For an.y given RA = (U, U, fln , w two elements a, b are called conjugated quasipro-jectzons ifa-oa C id, bVob C id, and a'ob = w. An RA is called a Q.relation algebraif its universe contains some conjugated quasiprojections.

These definitions say nothing about the intended realization, and their abstractnessis what makes them appropriate for describing broadly applicable operations. In [1]the intended interpretation is encapsulated into a membership relation E. All laws ofRA and a Q-relation algebra hold for any defiihition of E, and E c¢rnccts the abstractrelation algebras with a particular universe over which the relations are to range.

In particular, a Q-relation algebra defined over a nontrivial universe contains or-dered pairs or couples and the conjugated quasiprojections suggest that there are toolsfor selecting components of these couples. We define two such selectors over orderedcouples called conjugated projections and represent them by hd and t/.

VXY'{[XIY hd X), (31)Vx5'{XJ5'] t 1'). (32)

Page 10: BRL MR 3?bA BRL · 2011-05-15 · brl mr 3?ba memorandum report brl-mr-3784 brl n! program transformation cv) with abstract relation algebras n paul broome t october 1989 u--- approved

6

Note that they satisfy hd-ohd =_ iditf oil = id, and hd-oil Ew. Thus they qualify asconjugated quasiprojections. These projections select components of ordered couples.The following operators construct or perform related functions on couples.

[FIG] E- ( F o hdJ) n ( G o Wl). (33)

FOG- [hd o FlIt o G]. (31)

The following properties hold for construction and coupling operators. They all havesimilar proofs

[F U GIH ] E_ [FIH] U [GIH]. (3-5

[FIGU H] E [FIG]U[FIH]. (36)[FIG] n3 [H IK] -E [F n H)I(G n K)], (37)

(FOG) o (HCA') (F o H)O(Go A'), (3!,(FOG o W) o (RDS) E (FOG) o (RDW o S). (39)

(F o WOG) o (ROS) (FOG) o (W o RS), (40,(FDG)' (F"OG') (411

(FuG)OH _(FOHuGOH). (42,FO(Gu H) (FOGU F01). (43'

(FOG) n (HOK) E (F n H)O(G n K). (44,

4 Application to programs

The logical definitions of U, n, o,', hd. fl, C, f1 ], id, and ; (18-23) suggest an obviousimplementation with an SLD-resolution logic programming system in the logic ofpredicates of three variables For example, the goal X R Y would be represented asp(X. R, Y). Diversity and complement are discussed in section 4.1.

Note that no sentence introduces variables into the relation argument Thus everyliteral in the body of a program clause of the form p(X, R, Y) will contain only vari-ables R that were named In the clause head. Therefore if a gca! ;s. TIR. Y) where Ris ground. then every relation argument in every subgoal will be ground. We requirethat R be selected from a finite number of possible relations and relational constructs

We shall read R = S as 'R is equivalent to, but should be rewritten as, S.' But thisis represented in a logic program as the clause p(X, R, 1") : -p(X, S, Y). Conjunctionsare solved from left to right. Our intent is to match control with the order in whichvariables are bound. Therefore we partition the arguments of a relation into twostructured components, an 'input' and an 'output.' Predicates of single argumentsare extended to two arguments, both of which are the same value.

Page 11: BRL MR 3?bA BRL · 2011-05-15 · brl mr 3?ba memorandum report brl-mr-3784 brl n! program transformation cv) with abstract relation algebras n paul broome t october 1989 u--- approved

7

The FP systems of Backus [6] also depend upon operators, particularly composi-tion, to form more complex programs out of simpler ones. Berghammer and Ziever [71have given a relation algebra semantics for FP-like languages. Mili, Desharnais, andMili [81 have given heuristics for the design of deterministic programs from relationalequations. This paper describes a transformation system based on the operators.relations, and equations of a Q-relation algebra.

4.1 Diversity and Complement

The identity X id Y" requires unification of terms X and 1'. The diversity relationdepends on antiunification [91 and is denoted A di B. If A and B are both groundconstants then A di B will fail or succeed depending on whether they are the sameor different constants. On the other hand, if they contain unbound variables then theenvironment is extended to include that information as inequality constraints.

Terms with structure are solved recursively in a manner similar to unification. Ifthe two terms .4 and B have either different principal functors or ditlerent numbers ofarguments then antiunification succeeds without new inequality constraints. On theother hand, with the same principal functor and, say N, arguments, diversity in anyargument is enough for antiunification to succeed. Thus possibly A' new choice pointsare created by recursing the algorithm on these arguments. If one of the correspondingpairs of arguments can be determined to be different then no other alternatives needbe considered as the algorithm terminates successfully.

For example, consider the problem f(X,g(a)) di f(u,go')). The two solutions(inequality constraints) are X $ u and Y' $ a. On the other hand, the subgoalf(X. a) di f(Y, b) succeeds with no new inequality constraints.

Negation as finite failure cannot compute a complement. The goal BXY, X R Y isequivalent to 3XY, -,A R Y but negation by failure instead determines -'(3XY, A R Y).Although negation as finite failure has the usual logical interpretation for ground goals[10j. in the face of transformation we cannot be assured that a variable will be ground.

Constructive negation is an alternative to negation by failure. The elements ofare not actually constructed, but instead the resolution procedure is extended

with inequality constraints. Thus, solutions to nonground. negative subgoals areconstructed as a set of inequality constraints. Constructive negation has both a cleansemantics and the advantage of speeding up some computations [111.

Although relation complement is expressi.e, it is not monotonic because R C Sdo es not impl. W C 3 Transformations on programs built with R may become invalidif R? is extended. We will depend most heavily upon the other relation operators

Page 12: BRL MR 3?bA BRL · 2011-05-15 · brl mr 3?ba memorandum report brl-mr-3784 brl n! program transformation cv) with abstract relation algebras n paul broome t october 1989 u--- approved

including the diversity relation and avoid relation complement when possible.

4.2 Sequence construction and selection

A convenient way of sharing an input to more than one function is with Backusconstructor functional. We defined a similar constructor operation on relations. Theordered coupling operator creates an ordered couple as an output from a pair of inputsin a one to one fashion. Both operations are strict. While complex structures are madewith constructors, they are taken apart with hd and 1l. These are called selectors byBackus[6]. Selectors disassemble what the constructors and ordered couplers build.

While success of X hd o F Y indicates X is a couple, X hd o G Y would not failimmediatel. as X hd Z would be delayed until Z were bound. Thus we need a modelof lists with a special symbol such as [ ] to indicate the end of list. A sequence of oneelement A will be represented as [A], that is [.41B] where B = [1. The function nulltests sequences for emptiness and is an identity on [ ]. That is, null is just the singlepair [ ] []

\e also define a relation to deposit this symbol into a list construction. This emptysequencer is a constant function that ignores domain elements, returning the object[]. We also represent this function with the symbol []. It is defined as [c] = , nullThe following are some simple properties of null and [ ].

[AIB] o null =, (45)

(Ar-B) o null (46)

null o (A OB) E 0, (47)[] 1o null = [ ], (4SI

null o [AIB] E [null o Alnull o B]. (49)

5 Linear recursion

The closur of a relation R is R repeatedly composed with itself and is defined asR ° E idu RoR ° . Consider the program that finds the greatest common divisor of twonumbers. Here the realization is the natural numbers and subtract is defined onl onthat set. Thus [315] subtract Y would fail but [513] subtract 2 succeeds.

Page 13: BRL MR 3?bA BRL · 2011-05-15 · brl mr 3?ba memorandum report brl-mr-3784 brl n! program transformation cv) with abstract relation algebras n paul broome t october 1989 u--- approved

EXAMPLE 2 Greatest common divisor

gcd = ((id U [tllhd]) o [subtractl])" o (hd nil).

This simple program starts with two numbers and continually subtracts the second

number from the first until the numbers are the same. If necessary, it reorders the

numbers so that the largest is first. A trace of the computation on the couple [6118]

is [6118] = [1816] = [1216] => [616] =: 6. The monoid closure is not expressive enough

and is naturally oriented to a universe of elements without structure. We define a

linear recursion operator that extends the effect of the ordered coupler to lists and

list-like structures. This operator divides the structure into a couple with D, solves

for base cases with S, then combines the elements of a couple with C.

7r(D. S, C) = S U D o (idO7r(D, S, C)) o C. (50)

We can define monoid closure with ir as R' - ([wjR],id,tl). Also, we can definemap to apply the effect of a relation to each item of a sequence. Thus for example,

the goal (2, 3] map(id U subl) Y has four solutions for Y. The solutions would be

Y = {[2,3],[2,2],[l,3],[1,2]}. The definition is

map(R) = r(id, null, ROid). (51)

In our relations we collect inputs into a sinile structured input. For example, the Pro-

log goal append(A, B, C) is written as [AIB] append C. On the other hand, predicates

of a single argument become two argument, subrelations of the identity. An example

is 3 odd 3. These extensions are important because they allow us to use higher order

operators with Boolean valued relations to define new predicate operators.

All recursions that follow will be given in terms of r. They are preliminary to

the example transformations. The next definition is the function that cumulativelyconcatenates a sequence of sequences.

conc = (id, null, append), (52)

append = r([hd o hdltloid], (nullOid) otl, id). (53)

We can couple an item to each element of a sequence with either distr or disil as in

(6]. These functions can be simply defined in terms of r and the definitions exposetheir inherent symmetry.

disir = ir([hdoidltl13id], hd o null, id), (54)

distl E ;r((idChdjidtlj, til o null, id). (55)

To see what is happening here consider, for example, the function distr. It inputs anordered couple, a sequence and an item. The result is a sequence of couples each ofwhich has the given item as a second component. Schematically this is

Page 14: BRL MR 3?bA BRL · 2011-05-15 · brl mr 3?ba memorandum report brl-mr-3784 brl n! program transformation cv) with abstract relation algebras n paul broome t october 1989 u--- approved

10

[[A 1 , .", ANv]]" disir [[A1 IdC, [A21C1,- ',[AN C]].

Many relations can now be concisely defined in a single expression. For example, wecan define member on a couple, an element and a sequence. Thus member is simplya predicate (an identity) that tests the element for membership in the sequence. Forexample both ([31[2, 3,4]] member [31[2,3,4]]) and ([31[5]] nonmember [31[5]]) are true.

select = i(id, hd, tl). (56)

member = [hd n (tl o selec)tl]. (57)

nonmember - [hdldistl o map((hd o di) nfl)]. (58)

The following equations characterize not only some forms of loop merging but canalso propagate constraints. Since control is left to right, constraints on search are bestperformed as soon as possible. The following equation enables further propagation ofconstraints.

PROPOSITION I Merging linear recursions.

r(D, S o null, id) o w(id, null o T, C) =- ir(D, S o null o T, C).

The proof is by induction over relations defined on a well founded set. We unfol,each 7r-term in the expression i(D, S o null, id) o w(id, null o T, C) to arrive at

(S o null U D o (idOi(D, S o null, id))) o (null o 7" U (ido id, null o T, C)) o C).

Equations 46 and 47 eliminate the cross terms to give

S o null o null o TU D o (idnir(D, S o null, id)) o ((idOlr(id, null o T, C)) o C).

Now we can apply 38 to bring the two nr-terms together.

S o null o T U D o (idO7r(D, S o null, id) o r(id, null o T, C)) o C.

Applying the induction hypothesis we now have

• • II ==ONE"

Page 15: BRL MR 3?bA BRL · 2011-05-15 · brl mr 3?ba memorandum report brl-mr-3784 brl n! program transformation cv) with abstract relation algebras n paul broome t october 1989 u--- approved

S o null o T U D o (idOir(D, S o null o T, C)) o C.

Folding. we have w(D, S o null, id) o r(id, null o T, C) = x(D, S o null o T, C).

PROPOSITION 2 Propagation of constraints.

xr(D, S, (RIlid) o C) = r(D o (Rrid), S, C).

Again D must map a well founded set into lists. By induction and equation 34

7r(D, S, (RDid) o C) = S U D o (id3r(D, S, (RQid) o C)) o (RCid) o C,= S U D o (ROid) o (idOrr(D, S, (ROid) o C)) o C,

S U D o (ROid) o (id~r(D o (ROid), S, C)) o C,7(D o (ROid), S, C).

The relation R has changed positions. Now ROid tests on the way down, before anylarge structure has been built, instead of on the way back up. A simple consequence isthe equation map(F) o map(G) = map(F o G). This follows from these two equationsand the fact that map(R) =_ r(id, null, ROid).

If a concatenation of sequence is required to be empty, we can avoid the concate-

nation by requiring that each subsequence of the sequence be empty.

conc o null = map(null) o [ ]. (59)

This rule follows by induction from the definitions of conc, null, and map with equa-tions 8, 49, 39, and 40.

6 Transformations

We use the equations developed here to automatically accomplish a nontrivial programtransformation that is interesting for two reasons. Primarily, it does not rely on theBurstall and Darlington fold/unfold technique [12] but is instead directed by theoperator definitions and equations between relations. Therefore the method is easilNmechanized. Secondly, unlike Hogger's techniques [13], it is carried out using relationlevel reasoning without resorting to object level variables. This saves symbols andmakes the derivation more concise and broadly applicable.

Page 16: BRL MR 3?bA BRL · 2011-05-15 · brl mr 3?ba memorandum report brl-mr-3784 brl n! program transformation cv) with abstract relation algebras n paul broome t october 1989 u--- approved

12

The problem has two parts. The first part finds the list intersection of two lists.We may consider this program as a trivial example of a library program. Libraryprograms may well be written efficiently but combinations are often inefficient. Iftwo programs are written so that constraints are applied as early as possible, beforealternatives are created, the composition may have some constraints that are appliedtoo late.

A programmer should not expect to be penalized with the inefficiencies of libraryprograms. Our second program exhibits this problem. It is a clear, easy to under-stand program that simply tests to see if two sequences are disjoint. Using the rulesdeveloped earlier, we remove the inefficiencies in that program.

6.1 Disjointedness as empty intersection

The first part of this program finds the intersections of two lists by distributing onelist over the elements of the other, then finding those other elements that are membersof the list.

list-intersect = distr o map(member o [hd] U nonmember o [1) o cone. (60)

The program disjoint determines if two lists are disjoint by simply testing for anempty intersection. To return a positive answer we extend the model with the identityrelation on the constant yes. As defined, this program is unnecessarily inefficientalthough it is understandable in terms of its parts.

disjoint = list.intersect o null ow o yes. (61)

The transformation system applies the relation equations outwards in, from leftto right. After each successful rewrite the enclosing expression is attempted beforedeeper optimization is done to the subexpressions[14]. The first two recursions arewithin the definition of list-intersect. Let buildone represent the expression membcro[hd] U nonmember o []. Then,

list-intersect o null a distr o map(buildone) o cone o null.

We direct our attention to the two recursions in distromap(buildone) Both distr andmap are defined with ir so we merge and simplify them.

Page 17: BRL MR 3?bA BRL · 2011-05-15 · brl mr 3?ba memorandum report brl-mr-3784 brl n! program transformation cv) with abstract relation algebras n paul broome t october 1989 u--- approved

13

distr o map(buildonc) (hdOidli oi d, hdo null, id) o map(buildone),X i([hdOidltloid], hdo null, id) o r(id, null, buildoneOid),

- ([hdOidltloid), hdo null, buildoneQid),- r([hdoidllnid] o (buildonenid), hd o null, id),- ([hdOid o buildoneltlOid o id], hd o null, id),= r([hdDid o buildoneltloid], hd o null, id).

Next, conc o null is expanded to map(null) o [ ] which is 7r(id, null, nullid) o []. Thuslist-intersect o null is now two recursions followed by [ 1. This is

7r([hdC]id o buildoneltlOid], hd o null, id) o ,r(id, null, nullOid) o [].

Once again we merge recursions and propagate constraints to obtain

list-intersect o null r([hdOid o buildonetlid], hd o null, nullOid) o [3,= 7r([hdOid o buildone ltlia] o nullOid, hd o null. id) o [3,- v( [hdnid o buildone o nullltlOid o id], hd o null, id) o []

Now buildone is a union, over which we can distribute null to obtain buildoneonullmember o [hd] o null U nonmember o [ ] o null. In addition, one branch of the uniongoes away as [hdj o null always fails. Therefore, we have

disjoint 7r([hd~id o (nonmember o [o null)ItlOid o id], hd o null, id) o W o yes,ir([hdCid 0 (nonmember o [ J)ltllid], hd o null, id) o w o yes.

This is the order in which the implemented transformation system rewrites the originalprogram. The mechanically derived program for disjoint tests for nonmembershipbefore creating large structures. When the two lists differ at their first components,the remaining components need not be tested. Fr two lists of 30 elements, thisprogram is approximately 100 times faster than the original.

This is a significant speedup, but we should note that an arbitrary amount ofspeedup is possible with the converse operator. For example with sequential, left-to-right AND. the cost of solving X (parent' Y is much greater than the cost ofsolving X (parent-)* Y for a large family tree [15].

6.2 Eliminating intermediate lists

Wadler describes a deforestation method for avoiding intermediate lists [16]. He ap-plies it to a program to compute the sum of squares of numbers between I and N. The

Page 18: BRL MR 3?bA BRL · 2011-05-15 · brl mr 3?ba memorandum report brl-mr-3784 brl n! program transformation cv) with abstract relation algebras n paul broome t october 1989 u--- approved

14

method uses the unfold-fold method on recursive equations and applies to determin-istic programs. Transformations based on relation algebras extend these techniquesto nondeterministic computations in a verifiable way.

The program performs just three main steps. The program constructs a sequencefrom N to 1, squares every number, and sums the sequence. The first interestingobservation is that all of these operations are described by the ir operator.

w([idlsubl], eqO o [ ], id)o7r(id, null, sqroid)o7r(id, null o w o eqO, plus).

The realization for a Q-relation algebra requires the extra relations eqO, subl, sqr, andplus. These have the obvious definitions except that eqO is just the single pair {0, 0).

rhe first two recursions can be merged, with proposition 1, and the sqr operationcan be brought forward, with proposition 2, to obtain

7r([sqrlsubl] , eqO o [ ], id) o 7r(id, null o w o eqO, plus).

Once again the two recursions can be merged to obtain the result ir([sqrJsubl]. eqO, plus).

7 Conclusion

We have learned that the Q-relation algebras form a firm foundation for a transforma-tion oriented programming language. The abstract relation operators are appropriatefor describing the generic constructs that often arise in programming.

We have defined a model independent operator 7r that describes linear recursionsand have given two broadly applicable equations that merge recursions and propagateconstraints. They proviie an equational method for reasoning about nondeterministiccomputations.

The system based on these equations transforms these sample programs so thatthe result is essentially a different algorithm. This implementation shows that we canin some cases build new programs on previously constructed ones without the usualefficiency penalty from the combination.

Page 19: BRL MR 3?bA BRL · 2011-05-15 · brl mr 3?ba memorandum report brl-mr-3784 brl n! program transformation cv) with abstract relation algebras n paul broome t october 1989 u--- approved

15

Acknowledgements

These results would not have been possible without the valuable discussions I've hadwith Tom Myers and Dan Chester. Many thanks go to Roger Maddux for the time hehas taken to explain relation algebras. Thanks also go to Rich Kaste for reviewing thiswork and to Brint Cooper, Jerry Andersen, and Jagdish Chandra for their support.

References

[1] A. Tarski & S. Givant, "A formalization of set theory without variables," in Col-loquium publications #41, American Mathematical Society, Providence, RhodeIsland. 1987.

[2] D.H.D. Warren, "Higher-order extensions to Prolog: are they needed?," in MachineIntelligence 10, Hayes, Michie and Pao, ed., John Wiley & Sons, New York, NY,1982, 441-454.

[3] C. S. Peirce, "On the Algebra of Logic: A Contribution to the Philosophy ofNotation." American Journal of Mathematics VIl (1885).

[4] A. Tarski, "On the calculus of relations," The Journal of Symbolic Logic 6(1941),73-89.

[5] Roger D. Maddux, "Introductory course on relation algebras, finite-dimensionalcylindric algebras, and their interconnections," 1988, Notes.

[6] John Backus, "Can Programming Be Liberated from the von Neumann Style?; AFunctional Style and Its Algebra of Programs," Comm. ACM 21(1978), 613-641.

[7] R. Berghammer kI H. Ziever, "Relational Algebraic Semantics of Deterministic andNondeterministic Programs," Theoretical Computer Science43 (1986), 123-147.

[8] A. Mili, J. Desharnais & F. Mili, "Relational Heuristics for the Design of Deter-ministic Programs," Acta Informatica24 (1987), 239-276.

[9] A. Colmerauer, "Equations and inequationson finite and infinite trees," in FGCS'84Proceedings, 1984, 85-99.

Page 20: BRL MR 3?bA BRL · 2011-05-15 · brl mr 3?ba memorandum report brl-mr-3784 brl n! program transformation cv) with abstract relation algebras n paul broome t october 1989 u--- approved

16

[10] Joxan Jaffar, Jean-Louis Lassez & John Lloyd, "Completeness of the Negation asFailure Rule," in Proceedings of the 1983 IJCAI, 1983, 500-506.

[11] D. Chan, "Constructive Negation Based On the Completed Database," in LogicProgramming: Proceedings of the Fifth International Conference and Symposium,R A. Kowalski and K. A. Bowen,ed., MIT Press, Cambridge, MA, 1988, 111-125.

(12] R.M. Burstall & John Darlington, "A Transformation System for Developing Re-cursive Programs," J. Assoc. Comput. Mach.24 (Jan., 1977), 44-67.

[13] C.J. Hogger, "Derivation of Logic Programs," J. Assoc. Comput. Mach.28 (Apr.,1981). 372-392.

[14] Noor Islam, Tom Myers & Paul Broome, "A Simple Optimizer for FP-like Lan-guages," in Proc. ACM Cont on Functional Programming Languages and Com-puter Architecture, 1981, 33-39.

[15] Paul Broome, "Transformation of Parallel Programs with Higher Order RelationalOperators ," University of Delaware, Technical Report No. 86-02, 1985.

[16] Philip Wadler, "Deforestation: Transforming programs to eliminate trees," in LNCS,H . Ganzinger. ed. #300, Springer-Verlag, Berlin, 1988, 344-358.

Page 21: BRL MR 3?bA BRL · 2011-05-15 · brl mr 3?ba memorandum report brl-mr-3784 brl n! program transformation cv) with abstract relation algebras n paul broome t october 1989 u--- approved

No of No ofCopies Organizahion CoIles Organization

(LnO4s&., unlimitcdl 12 Administrator I Commander(Lncss., ljmjkd, 2 Defense Technical Info Center US Army Missile Command(Classiried) 2 ATTN: DTIC-DDA ATTN: AMSMI-RD-CS-R (DOC)

Cameron Station Redstone Arsenal, AL 35898-5010Alexandria, VA 22304-6145

1 Commander1 HQDA (SARD-TR) US Army Tank Automotive CommandWASH, DC 20310-0001 ATTN: AMSTA-TSL (Technical Library)

Warren, MI 48397.5000I Commander

US Army Materiel Command I DirectorATTN: AMCDRA-ST US Army TRADOC Analysis Command5001 Eisenhower Avenue ATTN: ATAA-SLAlexandria, VA 22333-0001 White Sands Missile Range, NM 88002-5502

1 Commander (Class. Onl)) CommandantUS Army Laboratory Command US Army Infantry SchoolATI-N: AMSLC-DL ATTN: ATSH-CD (Security Mgr.)Adelphi, MD 20783-1145 Fort Benning, GA 31905-5660

2 Commander (Lncla.s. onl) I CommandantArmament RD&E Center US Army Infantry SchoolUS Arm',' AMCCOM AT'TN: ATSH-CD-CSO-ORATTN: SMCAR-MSI Fort Benning, GA 31905-5660Picatinny Arsenal, NJ 07806-5000

1 The Rand Corporation2 Commander P.O. Box 2138

Armament RD&E Center Santa Monica, CA 90401-2138US Army AMCCOM (Class. onl)ATTN: SMCAR-TDC 1 Air Force Armament LaboratoryPicatinny Arsenal, NJ 07806-5000 ATTN: AFATL/DLODL

Eglin AFB, FL 32542-50001 Director

Benet Weapons Laboratory Aberdeen Proving GroundArmament RD&E Center Dir, USAMSAAUS Army AMCCOM AITN: AMXSY-DATTN: SMCAR-LCB-TL AMXSY-MP, H. CohenWatervlict, NY 12189-4050 Cdr, USATECOM

ATTN: AMSTE-TO-FI Commander Cdr, CRDEC, AMCCOM

US Army Armament, Munitions ATTN: SMCCR-RSP-Aand Chemical Command SMCCR-MU

ATTN: SMCAR-ESP-L SMCCR-MSIRock Island, IL 61299-5000

1 CommanderUS Army Aviation Systems CommandATTN: AMSAV-DACL4300 Goodfellow Blvd.St. Louis, MO 63120-1798

I DirectorUS Army Aviation Research

and Technology ActivityAmes Research CenterMoffett Field, CA 94035-1099

17

Page 22: BRL MR 3?bA BRL · 2011-05-15 · brl mr 3?ba memorandum report brl-mr-3784 brl n! program transformation cv) with abstract relation algebras n paul broome t october 1989 u--- approved

DISTRIBUTION LIST 18

No. Copies Organization No. Copies Organization

I Prof. Dale MillerComputer and Information SciencesUniversity of PennsylvaniaPhiladelphia, PA 19104-6389

2 DirectorUS Army Research OfficeATTN:Dr. William Sander

Dr. Jerry AndersenPO Box 12211Research Triangle Park, NC

27709-2211

Director I Dr. Sanjai NarainUS Army Tank Automotive Rand Corporation

Command 1700 Main StreetATTN:Dr. William Jackson Santa Monica. CA 90406

AMSTA-RSAWarren, MI 48397-5000

Aberdeen Proving GroundDr. Stephen Wolff, DirectorDivision of Networking and Director, BRL

Communications ATTN:SLCBR-SENational Science Foundation Mr. Morton A. Hirschberg1800 G St, NW Mr. Richard KasteWashington, DC 20550 Dr. A. Brinton Cooper, III

Mr. Michael John MuussProf. Anil Nerode Mr. Andrew ThompsonMathematical Sciences Institute Mr. Edwin 0. DavissonCornell University294 Caldwell HallIthaca, NY 14853-2602

Prof. Roger D. MadduxDepartment of Mathematics400 Carver HallIowa State UniversityAmes, Iowa 50011

Page 23: BRL MR 3?bA BRL · 2011-05-15 · brl mr 3?ba memorandum report brl-mr-3784 brl n! program transformation cv) with abstract relation algebras n paul broome t october 1989 u--- approved

DISTRIBUTION LIST 19

Dr. David ChanHewlett-Pachard LaboratoriesStoke Gifford, Bristol, England

Prof. Philip WadlerDepartment of Computing ScienceUniversity of GlasgowGlasgow G12 8QQ, Scotland

Page 24: BRL MR 3?bA BRL · 2011-05-15 · brl mr 3?ba memorandum report brl-mr-3784 brl n! program transformation cv) with abstract relation algebras n paul broome t october 1989 u--- approved

USER EVALUATION SHEET/CHANGE OF ADDRESS

Tl s laboratory undertakes a continuing effort to improve the quality of the reports it p.;shes. Ycr;rcoents/answers below will aid us in our efforts.

i. Does trts report satisfy a need? (Comment on purpose, related prc'ect, or other area of Interesv rthe report will be used.)

2. How, spe::*:caily, is the report being used? (rnforratlo. source, desgnr data, procedure, source cf !deas,etc.)

3. . as ,e :nf. rra:o- I n th s report leo to a r' q a-. tat ve sav!n;s as far as manr-hc.rs or dc a:s sa e:.

cFera ..q -csts av: Oed, or e!fIclen:-es ac-:e.e:, etz? I! sc, p:ease e.aborate.

4. Ge-' a: t--e 7s. .a: do y o : :t svc. : r, cru-eO t c I-rcve f tare rep:rt? 3 . ac e a "

z ua - a te r 'c a. c o ne nt .c r ra e, ,.I

FL ?er rt N7be r Divisicn Symbcl

Chezk here if desire tc be remrved frorr distribution list.

C7.ezk here for address chance.

Current address: Organizatcn _

AjJre~s

------------------------------ FOLD AND TAPE CLOSE .-----------------------------

NI PO$*A~iDirector NICISSU.S. Army Ballistic Research Laboratory IF ALLDATTN: SLCBP-DD-T((NEI) 114' IHI

Aberdeen Proving Ground, MD 21005-5066

OJIIC.ALBUSINESS REPLY LABELFIRST CtASS PIERAM NO I20t; ASMtNCI.ON 0 -

POSIAC, VItt 8( PAID IV DIPARIMLN' OF IHI ARlk-

DirectorU.S. Army Ballistic Research LaboratoryATTN: SLCBR-DD-T(NEI)Aberdeen Proving Ground, MD 21OC5-9989