unctional Programming with Bananas Lenses Envelopes and Ba rbed Wire Erik Meijer Maa rten okkinga Ross aterson Abstract develop calculus fo lazy functional rogramming based on recursion op erato rs a

unctional Programming with Bananas Lenses Envelopes and Ba rbed Wire Erik Meijer Maa rten okkinga Ross aterson Abstract develop calculus fo lazy functional rogramming based on recursion op erato rs a - Description

these op erato rs derive va rious algeb raic la ws that re useful in deriving and manipulating rograms shall sho that all example functions in Bird and adlers Intro duction to unctional Programming can b e exp ressed using these op erato rs Introduc ID: 29987 Download Pdf

213K - views

unctional Programming with Bananas Lenses Envelopes and Ba rbed Wire Erik Meijer Maa rten okkinga Ross aterson Abstract develop calculus fo lazy functional rogramming based on recursion op erato rs a

these op erato rs derive va rious algeb raic la ws that re useful in deriving and manipulating rograms shall sho that all example functions in Bird and adlers Intro duction to unctional Programming can b e exp ressed using these op erato rs Introduc

Similar presentations

Tags : these erato
Download Pdf

unctional Programming with Bananas Lenses Envelopes and Ba rbed Wire Erik Meijer Maa rten okkinga Ross aterson Abstract develop calculus fo lazy functional rogramming based on recursion op erato rs a

Download Pdf - The PPT/PDF document "unctional Programming with Bananas Lense..." is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.

Presentation on theme: "unctional Programming with Bananas Lenses Envelopes and Ba rbed Wire Erik Meijer Maa rten okkinga Ross aterson Abstract develop calculus fo lazy functional rogramming based on recursion op erato rs a"— Presentation transcript:

Page 1
unctional Programming with Bananas, Lenses, Envelopes and Ba rbed Wire Erik Meijer Maa rten okkinga Ross aterson Abstract develop calculus fo lazy functional rogramming based on recursion op erato rs asso ciated with data yp e de nitions. these op erato rs derive va rious algeb raic la ws that re useful in deriving and manipulating rograms. shall sho that all example functions in Bird and adler's \Intro duction to unctional Programming" can b e exp ressed using these op erato rs. Introduction Among the many st yles and metho dologies fo the construction of computer rograms the

Squiggol st yle in our opinion deserves attention from the functional rogramming communit The overall goal of Squiggol is to calculate rograms from their sp eci cation in the math- ematician calculates solutions to di erential equations, uses rithmetic to solve numerical roblems. It is not ha rd to state, rove and use la ws fo ell-kno wn op erations such as addition, multi- plication and |at the function level| comp osition. It is, ho ever, quite ha rd to state, rove and use la ws fo rbitra rily recursively de ned functions, mainly b ecause it is dicult to refer to the recursion scheme in

isolation. The algo rithmic structure is obscured using unstructured recursive de nitions. crack this roblem treating va rious recursion schemes as sepa rate higher rder functions, giving each notation of its wn indep endent of the ingredients with which it constitutes recursively de ned function. Universit of Nijmegen, Depa rtment of Info rmatics, o erno oiveld 6525 ED Nijmegen, e-mail: erik@cs.kun.nl CWI, Amsterdam Universit of Tw ente Imp erial College, London
Page 2
This philosophy is simila in spirit to the `structured rogramming' metho dology fo imp erative rogramming. The use

of rbitra ry goto's is abandoned in favour of structured control o rimitives such as conditionals and while-lo ops that replace xed patterns of goto's, so that rea- soning ab out rograms b ecomes feasible and sometimes even elegant. functional rograms the question is which recursion schemes re to b e chosen as basis fo calculus of rograms. shall consider several recursion op erato rs that re naturally asso ciated with algeb raic yp e de nitions. numb er of general theo rems re roven ab out these op erato rs and subsequently used to transfo rm rograms and rove their co rrectness. Bird and

Meertens [4, 18] have identi ed several la ws fo sp eci c data yp es (most notably nite lists) using which they calculated solutions to va rious rogramming roblems. By emb edding the calculus into catego rical framew rk, Bird and Meertens' rk on lists can b e extended to rbitra ry inductively de ned data yp es [17, 12]. Recently the group of Backhouse [1] has extended the calculus to relational framew rk, thus covering indeterminancy Indep endently aterson [21] has develop ed calculus of functional rograms simila in contents but very dissimila in app ea rance (lik many Australian animals) to

the rk referred to ab ove. Actually if one ricks through the syntactic di erences the la ws derived aterson re the same and in some cases slightly mo re general than those developp ed the Squiggolers. This pap er gives an extension of the theo ry to the context of lazy functional rogramming, i.e., fo us yp e is an -cp o and consider only continuous functions b et een yp es (catego rically re rking in the catego ry CPO). rking in the catego ry SET as done fo example Malcolm [17] Hagino [14 means that nite data yp es (de ned as initial algeb ras) and in nite data yp es (de ned as nal co-algeb

ras) constitute di erent rlds. In that case it is not p ossible to de ne functions induction (catamo rphisms) that re applicable to b oth nite and in nite data yp es, and rbitra ry recursive de nitions re not allo ed. rking in CPO has the advantage that the ca rriers of initial algeb ras and nal co-algeb ras coincide, thus there is single data yp e that comp rises b oth nite and in nite elements. The rice to b e paid ho ever is that pa rtialit of b oth functions and values b ecomes unavoidable. The data ype of lists shall illustrate the recursion patterns of interest means of the sp eci c data

yp e of cons- lists. So, the de nitions given here re actually sp eci c instances of those given in 4. Mo dern functional languages allo the de nition of cons-lists over some yp e putting: ::= Nil Cons The recursive structure of this de nition is emplo ed when writing functions that destruct list; these have b een called catamo rphisms (from the greek rep osition   meaning
Page 3
\do wnw rds" as in \catastrophe"). Anamo rphisms re functions (from the greek rep osition  meaning \up rds" as in \anab olism") that generate list of yp e from seed from unctions of yp e whose call-tree

has the shap e of cons-list re called hylomo rphisms (from the Aristotelian philosophy that fo rm and matter re one, o meaning \dust" \matter"). Catamo rphisms Let and then list-catamo rphism is function of the follo wing fo rm: Nil (1) Cons a; as )) as In the notation of Bird&W adler [5] one ould write foldr write catamo rphisms wrapping the relevant constituents b et een so called banana rack ets: b; (2) Countless list ro cessing functions re readily recognizable as catamo rphisms, fo example length Num filter with bool length 0; where filter Nil; where as Cons a; as as; Sepa rating the

recursion pattern fo catamo rphisms from its ingredients and mak es it feasible to reason ab out catamo rphic rograms in an algeb raic example the usion La fo catamo rphisms over lists reads: b; c; as as Without sp ecial notation pinp ointing catas, such as foldr ould b e fo rced to fo r- mulate the fusion la as follo ws. Let h; b e given Nil Nil Cons a; as )) as Cons a; as )) as then if and as as clumsy of stating such simple algeb raic rop ert
Page 4
Anamo rphisms Given redicate bool and function list-anamo rphism is de ned as: Nil; (3) Cons a; otherwise where a; Anamo rphisms re

not ell-kno wn in the functional rogramming folklo re, they re called unfold Bird&W adler, who sp end only few rds on them. denote anamo rphisms wrapping the relevant ingredients b et een concave lenses: g; (4) Many imp o rtant list-valued functions re anamo rphisms; fo example zip k which `zips' pair of lists into list of pairs. zip g; as; bs as Nil bs Nil Cons a; as Cons b; bs )) (( a; as; bs )) Another anamo rphism is iterate which given constructs the in nite list of iterated appli- cations of to iterate g; false where a; use to denote the constant function x:c Given the map function

applies to every element in given list. Nil Nil Cons a; as )) Cons a; as Since list app ea rs at b oth sides of its yp e, might susp ect that map can b e written b oth as catamo rphism and as an anamo rphisms. Indeed this is the case. As catamo rphism: Nil; where bs Cons a; bs and as anamo rphism g; where as as Nil and Cons a; as )) a; as Hylomo rphisms recursive function whose call-tree is isomo rphic to cons-list, i.e., linea recursive function, is called hylomo rphism. Let and and
Page 5
and bool then these determine the hylomo rphism c; (5) otherwise where b; This is exactly the

same structure as an anamo rphism except that Nil has b een replaced and Cons write hylomo rphisms wrapping the relevant pa rts into envelop es. [( c; g; )] (6) hylomo rphism co rresp onds to the comp osition of an anamo rphism that builds the call-tree as an explicit data structure and catamo rphism that reduces this data object into the required value. [( c; g; )] c; g; ro of of this equalit will b e given in 15. An rchet ypical hylomo rphism is the facto rial function: fac [( 1; g; )] n; ramo rphisms The hylomo rphism de nition of the facto rial ma yb e co rrect but is unsatisfacto ry from

theo retic p oint of view since it is not inductively de ned on the data yp e num ::= num There is ho ever no `simple' such that fac The roblem with the facto rial is that it \eats its rgument and eeps it to o" [27], the rute fo rce catamo rphic solution ould therefo re have fac return pair n; !) to b e able to compute )! ramo rphisms ere investigated Meertens [19 to cover this pattern of rimitive recursion. yp e num pa ramo rphism is function of the fo rm: (7) lists pa ramo rphism is function of the fo rm: Nil Cons a; as )) as; as
Page 6
write pa ramo rphisms wrapping the relevant

constituents in ba rb ed wire b; i thus ma write fac 1; i where The function tails which gives the list of all tail segments of given list is de ned the pa ramo rphism tails Cons Nil; Nil where as; tls Cons Cons a; as tls Algeb raic data ypes In the receding section have given sp eci c notations fo some recursion patterns in connec- tion with the pa rticula yp e of cons-lists. In rder to de ne the notions of cata-, ana-, hylo- and pa ramo rphism fo rbitra ry data yp es, no resent generic theo ry of data yp es and functions on them. this consider recursive data yp e (also called `algeb raic'

data yp e in Miranda) to b e de ned as the least xed p oint of functo uncto rs bifuncto is bina ry op eration taking yp es into yp es and functions into functions such that if and then and which reserves identities and comp osition: id id id Bifuncto rs re denoted monofuncto is una ry yp e op eration which is also an op eration on functions, that reserves the identit and comp osition. use to denote monofuncto rs. In view of the notation write the application of functo as p ost x: In will sho that is functo indeed. The data yp es found in all current functional languages can b e de ned using

the follo wing basic functo rs. Pro duct The (lazy) ro duct of yp es and and its op eration on functions re de ned as: d; D; give the de nitions of va rious concepts of catego ry theo ry only fo the sp ecial case of the catego ry CPO. Also `functo rs' re really endo-functo rs, and so on.
Page 7
x; x; Closely related to the functo re the rojection and tupling combinato rs: x; x; x; Using ; and can exp ress as can also de ne using and the doubling combinato x; since Sum The sum of and and the op eration on functions re de ned as: 0; 0; 1; 1; The rbitra rily chosen numb ers and re used

to `tag' the values of the summands so that they can b e distinguished. Closely related to the functo re the injection and selection combinato rs: 0; 1; 0; 1; with which can write Using which removes the tags from its rgument, and i; can de ne Arro The op eration that fo rms the function space of continuous functions from to has as action on functions the `wrapping' function: Often will use the alternative notation where have sw app ed the rro already so that up on application the rguments need not b e moved, thus lo calizing the changes o ccurring during calculations. The functional wraps its

-ed rgument b et een and
Page 8
Closely related to the re the combinato rs: curry x; uncurry x; eval f; Note that is contra-va riant in its rst rgument, i.e. Identit Constants The identit functo is de ned on yp es as and on functions as Any yp e induces functo with the same name whose op eration on objects is given CD and on functions fD id Lifting mono-functo rs and bi-functo de ne the mono-functo rs and fo b oth yp es and functions In view of the rst equation need not write pa renthesis in Notice that in the bi-functo is `lifted' to act on functo rs rather than on objects; is

itself mono-functo r. Sectioning Analogous to the sectioning of bina ry op erato rs, and de ne sectioning of bi-functo rs id hence and id Simila rly can de ne sectioning of in its second rgument, i.e. and It is not to o dicult to verify the follo wing rop erties of sectioned functo rs: fo all (8) (( (9) aking thus gives some nice la ws fo function comp osition.
Page 9
La ws fo the basic combinato rs There re va rious equations involving the ab ove combinato rs, state nothing but few of these. In pa rsing an exp ression function comp osition has least binding p o er while binds

stronger than strict id id strict nice la relating and is the abides la (10) ria The one element yp e is denoted and can b e used to mo del constants of yp e nulla ry functions of yp e The only memb er of called void is denoted () In some examples use fo given redicate bool the function: a; true a; false thus mo dels the familia conditional if then else The function OID maps its rgument to void: OID () Some la ws that hold fo these functions re: OID OID )? In rder to mak recursion explicit, use the op erato de ned as: where
Page 10
assume that recursion (lik is ell de ned in the

meta-language. Let b e functo rs and fo any yp e Such is called p olymo rphic function. natural transfo rmation is family of functions (omitting subscripts whenever p ossible) such that: (11) As convenient sho rthand fo 11 use to denote that is natural trans- fo rmation. The \Theo rems ree!" theo rem of adler, deBruin and Reynolds [28 9, 22] states that any function de nable in the p olymo rphic -calculus is natural transfo rmation. If is de ned using one can only conclude that (11) holds fo strict Recursive ypes After all this stu on functo rs have nally rmed ourselves suciently to abstract

from the p eculia rities of cons-lists, and fo rmalize recursively de ned data yp es in general. Let b e monofuncto whose op eration of functions is continuous, i.e., all monofuncto rs de ned using the ab ove basic functo rs any of the map-functo rs intro duced in Then there exists yp e and strict functions in and out (omitting subscripts whenever p ossible) which re each others inverse and even id in out [6, 23, 16 24 30 12 ]. let denote the pair L; in and sa that it is \the least xed p oint of ". Since in and out re each others inverses have that is isomo rphic to and indeed is upto isomo

rphism xed p oint of example taking have that in de nes the data yp e of cons- lists over fo any yp e If put Nil in and Cons in get the mo re familia Nil Cons Another example of data yp es, bina ry trees with leaves of yp e results from taking the least xed p oint of Backw rd lists with elements of yp e sno c lists as they re sometimes called, re the least xed p oint of Natural numb ers re sp eci ed as the least xed p oint of Recursion Schemes No that have given generic of de ning recursive data yp es, can de ne cata-, ana-, hylo- and pa ramo rphisms over rbitra ry data yp es. Let L; in A; 10

Page 11
then de ne out (12) in (13) '; (14) f: id out (15) When no confusion can rise omit the subscripts. De nition (13) agrees with the de nition given in 2; where wrote e; no write De nition (14) agrees with the info rmal one given ea rlier on; the notation g; of no b ecomes (( OID ?) De nition (15) agrees with the ea rlier one in the sense that taking and OID mak es g; )] equal to '; De nition (15) agrees with the description of pa ramo rphisms as given in in the sense that b; i equals here. Program Calculation La ws Rather than letting the rogrammer use explicit recursion,

encourage the use of the ab ove xed recursion patterns roviding shopping list of la ws that hold fo these patterns. each -mo rphism, with cata, ana, pa ra give an evaluation rule which sho ws ho such mo rphism can b e evaluated, Uniqueness Prop ert canned induction ro of fo given function to b e -mo rphism, and fusion la which sho ws when the comp osition of some function with an -mo rphism is again an -mo rphism. All these la ws can b e roved mere equational reasoning using the follo wing rop erties of general recursive functions. The rst one is `free theo rem' fo the xed p oint op erato g

h strict (16) Theo rem (16) app ea rs under di erent names in many places [20, 8, 15, 7, 25 13, 31]. In this pap er it will b e called xed p oint fusion The strictness condition in (16) can sometimes b e relaxed using g g (17) Other references re elcome. 11
Page 12
Fixed p oint induction over the redicate g; will rove (17). hylomo rphisms rove that they can b e split into an ana- and catamo rphism and sho ho computation ma b e shifted within hylomo rphism. numb er of derived la ws sho the relation b et een certain cata- and anamo rphisms. These la ws re not valid in SET. The

hylomo rphism la ws follo from the follo wing theo rem: id (18) Catamo rphisms Evaluation rule The evaluation rule fo catamo rphisms follo ws from the xed p oint rop ert f in (CataEval It states ho to evaluate an application of to an rbitra ry element of (returned the constructo in ); namely apply recursively to the rgument of in and then to the result. cons lists Nil Cons where and id id with catamo rphism the evaluation rule reads: Nil (19) Cons id (20) i.e. the va riable free fo rmulation of (1). Notice that the constructo rs, here Nil Cons re used fo pa rameter pattern matching. UP fo

catamo rphisms The Uniqueness Prop ert can b e used to rove the equalit of functions without using induction explicitly in (CataUP) ypical induction ro of fo sho wing tak es the follo wing steps. Check the induction base: Assuming the induction hyp othesis ro ceed calculating: in induction hyp othesis evaluation rule (CataEval) in 12
Page 13
to conclude that The schematic set-up of such ro of is done once and fo all, and built into la (CataUP). re thus saved from the standa rd ritual steps; the last lines in the ab ove calculation, plus the decla ration that `b induction' the ro of

is complete. The pa rt of the ro of fo (CataUP) follo ws directly from the evaluation rule fo cata- mo rphisms. the pa rt use the xed p oint fusion theo rem (17) with := := := in out and := This gives us in out in out and since in out id re done. usion la fo catamo rphisms The usion La fo catamo rphisms can b e used to trans- fo rm the comp osition of function with catamo rphism into single catamo rphism, so that intermediate values can b e avoided. Sometimes the la is used the other round, i.e. to split function, in rder to allo fo subsequent optimizations. (CataF usion ) The fusion la can b

e roved using xed p oint fusion theo rem (17) with := := out := in out and := (( slight va riation of the fusion la is to replace the condition i.e. is strict. strict (CataF usion' ) This la follo ws from (16). In actual calculations this latter la is mo re valuable as its appli- cabilit conditions re on the whole easier to check. Injective functions re catamo rphisms Let b e strict function with left-inverse then fo any have strict id (21) aking in immediatly get that any strict injective function can b e written as catamo rphism. in strict id (22) Using this latter result can write out in

terms of in since out out in in in 13
Page 14
Catamo rphisms reserve strictness The given la ws fo catamo rphisms all demonstrate the imp o rtance of strictness, generally of the b ehaviour of function with resp ect to The follo wing \p o o man's strictness analyser" fo that reason can often b e put into go o d use. F :: (23) The ro of of (23) is xed p oint induction over Sp eci cally fo catamo rphisms have if is strictness reserving. The pa rt of the ro of directly follo ws from (23) and the de nition of catamo rphisms. The other round is sho wn as follo ws remise in in evaluation

rule reserves strictness Examples Unfold-F old Many transfo rmations usually accomplished the unfold-simplify-fold tech- nique can b e restated using fusion. Let Num Nil Cons where Num and id id b e the yp e of lists of natural numb ers. Using fusion derive an ecient version of sum squares where sum and squares Nil Cons SQ id Since sum is strict just sta rt calculating aiming at the discovery of that satis es the condition of (CataF usion'). sum Nil Cons id sum Nil sum Cons SQ id Nil ((+) id sum SQ id Nil ((+) SQ id id sum Nil ((+) SQ id sum 14
Page 15
and conclude that sum squares

Nil ((+) SQ id slightly mo re complicated roblem is to derive one-pass solution fo average DIV sum length Using the tupling lemma of okkinga [10] simple calculation sho ws that average DIV (+) id (+ Accumulating Arguments An imp o rtant item in the functional rogrammer's bag of tricks is the technique of accumulating rguments where an extra pa rameter is added to function to accumulate the result of the computation. Though stated here in terms of catamo rphisms over cons-lists, the same technique is applicable to other data yp es and other kind of mo rphisms as ell. where (24) Theo rem (24)

follo ws from the fusion la taking Accu with Accu Given the naive quadratic de nition of reverse as catamo rphism Nil where as as Cons a; Nil )) can derive linea time algo rithm instantiating (24) with := and := Cons to get function which accumulates the list b eing reversed as an additional rgument: id where as bs as Cons a; bs )) Here is the function that app ends lists, de ned as as bs id as bs where bs Cons a; bs In general catamo rphisms of higher yp e fo rm an interesting class themselves as they co rresp ond to attribute gramma rs [11]. Anamo rphisms Evaluation rule The evaluation rule

fo anamo rphisms is given y: out (AnaEval 15
Page 16
It sa ys what the result of an rbitra ry application of lo oks lik e: the constituents ro duced applying out can equivalently b e obtained rst applying and then applying recursively to the result. Anamo rphisms re real old fussp ots to explain. instantiate (AnaEval) fo cons list de ne: hd out tl out is nil true false out Assuming that OID ?) nd after little calculation that: is nil hd tl which co rresp onds to the cha racterization of unfold given Bird and adler [5] on page 173. UP fo anamo rphisms The UP fo anamo rphisms is

slightly simpler than the one fo cata- mo rphisms, since the base case do es not have to b e check ed. out (AnaUP ) rove it can use xed p oint fusion theo rem 16 with := := in out and := in This gives us in out in and again since in out id re done. usion la fo anamo rphisms The strictness requirement that as needed fo catamo r- phisms can b e dropp ed in the anamo rphism case. The dual condition of fo strictness is which is vacuously true. (AnaF usion ) This la can b e roved xed p oint fusion theo rem (16) with := := in and := in 16
Page 17
Any surjective function is an anamo rphism

The results (21) and (22) can b e dualized fo anamo rphisms. Let surjective function with right-inverse then fo any have id (25) since The sp ecial case where equals out yields that any surjective function can b e written as an anamo rphism. out id (26) As in has right-inverse out can exp ress in using out in out out in out Examples Refo rmulated in the lense notation, the function iterate b ecomes: iterate id have id OID id false ?) (= id f; false in the notation of section ). Another useful list-p ro cessing function is takewhile which selects the longest initial segment of list all whose

elements satisfy In conventional notation: takewhile Nil Nil takewhile Cons as Nil; Cons takewhile as otherwise The anamo rphism de nition ma lo ok little daunting at rst: takewhile OID id )?) out The function while contains all rep eated applications of as long as redicate holds: while takewhile iterate Using the fusion la (after rather long calculation) can sho that while OID id ?) 17
Page 18
Hylomo rphisms Splitting Hylomo rphisms In rder to rove that hylomo rphism can b e split into an anamo r- phism follo ed catamo rphism '; (HyloSplit) can use the total fusion theo rem (18).

Shifting la Hylomo rphisms re nice since their decomp osabilit into cata- and an anamo r- phism allo ws us to use the resp ective fusion la ws to shift computation in out of hylomo r- phism. The follo wing shifting la sho ws ho computations can b e shifted within hylomo r- phism. ; '; (HyloShift) The ro of of this theo rem is straightfo rw rd. ; de nition hylo f:' f:' de nition hylo '; An admittedly humbug example of (HyloShift) sho ws ho left linea recursive functions can b e transfo rmed into right linea recursive functions. Let id id and id id de ne the functo rs which exp ress left

resp ectively right linea recursion, then if have ?] SWAP ; f ?] SW AP SW AP ?] ?] where SWA id 18
Page 19
Relating cata- and anamo rphisms rom the splitting and shifting la (HyloShift), (HyloSplit) and the fact that '; out and in; can derive numb er of interesting la ws which relate cata- and anamo r- phisms with each other. in out (27) Using this la can easily sho that out (28) in (29) in (30) out (31) This set of la ws will b e used in 5. rom the total fusion theo rem (18) can derive: id id (32) Example: Re ecting bina ry trees The yp e of bina ry trees with leaves of yp e is

given tree A; in where and id id Re ecting bina ry tree can b e de ned y: reflect in SW AP where SWA id id simple calculation roves that reflect reflect id reflect reflect SW AP SW AP SWAP out in SWAP SW AP out in SWA id id ramo rphisms The evaluation rule fo pa ramo rphisms is in id (P raEval 19
Page 20
The UP fo pa ramo rphisms is simila to that of catamo rphisms: in id (P raUP) The fusion la fo pa ramo rphisms reads strict id (P raF usion ) Any function (of the right yp e of course!) is pa ramo rphism. in The usefulness of this theo rem can b e read from its ro of. in de nition

(15) g:f in id out functo calculus g:f in out Example: comp osing pa ramo rphisms from ana- and catamo rphisms nice result is that any pa ramo rphism can b e written as the comp osition of cata- and an anamo rphism. Let L; in b e given, then de ne id M; IN natural numb ers get Num Num i.e. Num in which is the yp e of lists of natural numb ers. No de ne preds as follo ws: preds out the naturals get preds id out that is given natural numb er the exp ression preds yields the list 1; : ; Using preds sta rt calculating: 20
Page 21
preds out f:' out f:' id id id out f:' id out Thus

preds Since IN id immediately get preds IN rametrized ypes In have de ned fo the map function Tw la ws fo re id id and These la ws recisely state that is functo r. Another cha racteristic rop ert of map is that it leaves the `shap e' of its rgument unchanged. It turns out that any pa rametrized data yp e comes equipp ed with such map functo r. pa rametrized yp e is yp e de ned as the least xed p oint of sectioned bifuncto r. Contra ry to Malcolms app roach [17 map can b e de ned b oth as catamo rphism and as an anamo rphism. Maps Let b e bi-functo r, then de ne the functo on objects as the pa

rametrized yp e where in and on functions as: in (33) Since from (27) immediately get an alternative version of as an anamo rphism: (( out uncto rialit of is calculated as follo ws: de nition in in (29) 21
Page 22
in (9) in (( de nition Maps re shap e reserving. De ne SHAPE OID then SHAPE OID SHAPE cons-list Nil Cons with and id get id out rom the UP fo catas nd that this confo rms to the usual de nition of map. Nil Nil Cons Cons Other imp o rtant la ws fo maps re facto rization [26] and romotion [4]. (34) (( (35) strict (36) (37) No kno that is functo r, can recognize that in y and

out y re natural transfo rmations. in in out out Iterate romotion Recall the function iterate id the follo wing la turns an algo rithm into an algo rithm, under the assumption that evaluating tak es steps. iterate iterate (38) La (38) is an immediate consequence of the romotion la fo anamo rphisms (37). Interestingly ma also de ne iterate as cyclic list: iterate xs:Cons x; xs )) and use xed p oint fusion to rove (38). 22
Page 23
Map-Reduce facto rization data yp e in with is called free -t yp e over free yp e can alw ys write strict catas as taking and get in id tau join id tau

join where tau in and join in If de ne the reduction with as '= id (39) the facto rization la (34) sho ws that catamo rphisms on free yp e can b e facto red into map follo ed reduce. id id id '= The fact that tau and join re natural transfo rmations give evaluation rules fo and '= on free yp es. tau tau '= tau id join join '= join '= Ea rly Squiggol as based completely on map-reduce facto rization. Some of these la ws from the go o d old da ys; reduce romotion and map romotion '= join= '= '= join= join=  Monads Any free yp e gives rise to monad [17], in the ab ove notation, tau join= 

since: join= tau id join= tau id join= join= join= join= 23
Page 24
adler [29] gives tho rough discussion on the concepts of monads and their use in functional rogramming. Conclusion have considered va rious patterns of recursive de nitions, and have resented lot of la ws that hold fo the functions so de ned. Although have illustrated the la ws and the recursion op erato rs with examples, the usefulness fo ractical rogram calculation might not b e evident to every reader. Unfo rtunately have not enough space here to give mo re elab o rate examples. There re mo re asp ects to rogram

calculation than just series of combining fo rms (lik and la ws ab out them. calculating la rge rograms one certainly needs high level algo rithmic theo rems. The rk rep o rted here rovides the necessa ry to ols to develop such theo rems. the theo ry of lists Bird [3] has sta rted to do so, and with success. Another asp ect of rogram calculation is machine assistance. Our exp erience |including that of our colleagues| sho ws that the size of fo rmal manipulations is much greater than in most textb o oks of mathematics; it ma ell b e compa rable in size to \computer algeb ra" as done in systems

lik MA CSYMA, Maple, Mathematica etc. rtunately it also app ea rs that most manipulations re easily automated and, mo reover, that quite few equalities dep end on natural transfo rmations. Thus in several cases yp e checking alone suces. Clea rly machine assistance is fruitful and do es not seem to b e to o dicult. Finally observe that catego ry theo ry has rovided several notions and concepts that ere indisp ensable to get clean and smo oth theo ry; fo example, the notions of functo and natural transfo rmation. (While reading this pap er, catego ry theo rist ma recognize several other

notions that silently used). Without doubt there is much mo re catego rical kno wledge that can b e useful fo rogram calculation; re just at the b eginning of an exciting development. Ackno wledgements Many of the results resented here have fo the case SET already ap- p ea red in numerous notes of the STOP Algo rithmics Club featuring among others Roland Backhouse, Johan Jeuring, Doaitse Swierstra, Lamb ert Meertens, Nico erw er and Jaap van der oude. Graham Hutton rovided many useful rema rks on draft versions of this pap er. 24
Page 25
References [1] Roland Backhouse, Jaap van der

oude, Ed o ermans, and Grant Malcolm. relational theo ry of yp es. echnical Rep o rt ??, TUE, 1991. [2] Rudolf Berghammer. On the use of comp osition in transfo rmational rogramming. ech- nical Rep o rt TUM-I8512, TU M  unchen, 1985. [3] R. Bird. An intro duction to the theo ry of lists. In M. Bro edito r, Logic of Program- ming and Calculi of Discrete Design pages 3{42. Sp ringer erlag, 1987. Also echnical Monograph PRG-56, Oxfo rd Universit Octob er 1986. [4] Richa rd Bird. Constructive functional rogramming. In M. Bro edito r, Ma rktob erdo rf International Summer scho ol on Constructive

Metho ds in Computer Science NA TO Ad- vanced Science Institute Series. Sp ringer erlag, 1989. [5] Richa rd Bird and Phil adler. Intro duction to unctional Programming Prentice-Hall, 1988. [6] R. Bos and C. Hemerik. An intro duction to the catego ry-theo retic solution of recursive domain equations. echnical Rep o rt TRCSN 88/15, Eindhoven Universit of echnology Octob er 1988. [7] Manfred Bro ransfo rmation pa rallel ablaufender Programme PhD thesis, TU M  unchen, M  unchen, 1980. [8] A. de Bruin and E.P de Vink. Retractions in compa ring Prolog semantics. In Computer Science in the

Netherlands 1989 pages 71{90. SION, 1989. [9] eter de Bruin. Naturalness of p olymo rphism. echnical Rep o rt CS 8916, RUG, 1989. [10] Maa rten okkinga. upling and mutumo rphisms. The Squiggolist 1(4), 1989. [11] Maa rten okkinga, Johan Jeuring, Lamb ert Meertens, and Erik Meijer. ranslating at- tribute gramma rs into catamo rphisms. The Squiggolist 2(1), 1991. [12] Maa rten okkinga and Erik Meijer. Program calculation rop erties of continuous algeb ras. echnical Rep o rt 91-4, CWI, 1991. [13] C. Gunter, Mosses, and D. Scott. Semantic domains and denotational semantics. In Ma rktob erdo rf

International Summer scho ol on Logic, Algeb ra and Computation 1989. to app ea in: Handb o ok of Theo retical Computer Science, No rth Holland. [14] asuy Hagino. Co datat yp es in ML. Journal of Symb olic Computation 8:629{650, 1989. 25
Page 26
[15] J.Arsac and Ko drato . Some techniques fo recursion removal. CM oplas 4(2):295{ 322, 1982. [16] D.J. Lehmann and M.B. Smyth. Algeb raic sp eci cation of data yp es: synthetic ap- roach. Math. Systems Theo ry 14:97{139, 1981. [17] Grant Malcolm. Algeb raic yp es and Program ransfo rmation PhD thesis, Universit of Groningen, The

Netherlands, 1990. [18] Lamb ert Meertens. Algo rithmics to rds rogramming as mathematical activit In Pro ceedings of the CWI symp osium on Mathematics and Computer Science pages 289{334. No rth-Holland, 1986. [19] Lamb ert Meertens. ramo rphisms. app ea in rmal Asp ects of Computing, 1990. [20] John-Jules Ch. Mey er. Programming calculi based on xed p oint transfo rmations: seman- tics and applications PhD thesis, rije Universiteit, Amsterdam, 1985. [21] Ross aterson. Reasoning ab out unctional Programs PhD thesis, Universit of Queens- land, Brisbane, 1988. [22] John C. Reynolds. yp es

abstraction and pa rametric p olymo rphism. In Info rmation Pro- cessing '83 No rth Holland, 1983. [23] David A. Schmidt. Denotational Semantics Allyn and Bacon, 1986. [24] M.B. Smyth and G.D. Plotkin. The catego ry-theo retic solution of recursive domain equa- tions. SIAM Journal on Computing 11(4):761{785, Novemb er 1982. [25] Joseph E. Sto Denotational Semantics, The Scott-Strachey App roach to Programming Language Theo ry The MIT ress, 1977. [26] Nico erw er. Homomo rphisms, facto risation and romotion. The Squiggolist 1(3), 1990. Also technical rep o rt RUU-CS-90-5, Utrecht Universit

1990. [27] Phil adler. Views: fo pattern matching to cohabit with data abstraction. ech- nical Rep o rt 34, Programming Metho dology Group, Universit of G oteb o rg and Chalmers Universit of echnology Ma rch 1987. [28] Philip adler. Theo rems fo free In Pro c. 1989 CM Conference on Lisp and unctional Programming pages 347{359, 1989. [29] Philip adler. Comp rehending monads. In Pro c. 1990 CM Conference on Lisp and unctional Programming 1990. [30] M. and. Fixed p oint constructions in rder enriched catego ries. Theo retical Computer Science 8, 1979. 26
Page 27
[31] Hans Zierer.

Programmierung mit funktionsobjecten: Konstruktive erzeugung semantische b ereiche und anw endung auf die pa rtielle ausw ertung. echnical Rep o rt TUM-I8803, TU M  unchen, 1988. 27