
The essence of functional programming Philip Wadler UniversityofGlasgow Abstract This pap er explores the use monads to structure functional programs No prior knowledge of monads or category theory is required Monads increase the ease with which programs may b e mo died They can mimic the eect of impure features such as exceptions state and continuations and also provide eects not easily achieved with such features The typ es of a program reect which eects o ccur The rst section is an extended example of the use of monads A simple inter preter is mo died to supp ort various extra features error messages state output and nondeterministic choice The second section describ es the relation b etween monads and continuationpassing style The third section sketches how monads are used in a compiler for Haskell that is written in Haskell Intro duction Shall I b e pure or impure Pure functional languages suchasHaskell or Miranda oer the p ower of lazy eval uation and the simplicity of equational reasoning Impure functional languages suchas Standard ML or Scheme oer a tempting spread of features such as state exception handling or continuations One factor that should inuence mychoice is the ease with which a program can b e mo died Pure languages ease change by making manifest the data up on whicheach op eration dep ends But sometimes a seemingly small change may require a program in a pure language to b e extensively restructured when judicious use of an impure feature may obtain the same eect by altering a mere handful of lines Say I write an interpreter in a pure functional language To add error handling to it I need to mo dify the result typ e to include error values and at each recursive call to check for and handle errors appropriately Had I used an impure language with exceptions no such restructuring would b e needed Authors address Department of Computing Science University of Glasgow Glasgow G QQ Scotland Email wadlerdcsglasgowacuk Presented as an invited talk at th Annual Symposium on Principles of Programming Languages Al buquerque New Mexico January This version diers slightly from the conference pro ceedings To add an execution count to it I need to mo dify the the result typ e to include such acount and mo dify each recursive call to pass around suchcounts appropriately Had I used an impure language with a global variable that could b e incremented no such restructuring would b e needed To add an output instruction to it I need to mo dify the result typ e to include an output list and to mo dify each recursive call to pass around this list appropriately Had I used an impure language that p erformed output as a side eect no such restructuring would b e needed Or I could use a monad This pap er shows how to use monads to structure an interpreter so that the changes mentioned ab ove are simple to make In each case all that is required is to redene the monad and to make a few lo cal changes This programming style regains some of the exibilityprovided byvarious features of impure languages It also may apply when there is no corresp onding impure feature The technique applies not just to interpreters but to a wide range of functional pro grams The GRASP team at Glasgow is constructing a compiler for the functional lan guage Haskell The compiler is itself written in Haskell and uses monads to go o d eect Though this pap er concentrates on the use of monads in a program tens of lines long it also sketches our exp erience using them in a program three orders of magnitude larger Programming with monads strongly reminiscentofcontinuationpassing style CPS and this pap er explores the relationship b etween the two In a sense they are equivalent CPS arises as a sp ecial case of a monad and any monad maybeemb edded in CPS by changing the answer typ e But the monadic approachprovides additional insight and allows a ner degree of control The concept of a monad comes from category theory but this pap er assumes no prior knowledge of suc h arcana Rather it is intended as a gentle intro duction with an emphasis on why abstruse theory maybeofinterest to computing scientists The examples will b e given in Haskell but no knowledge of that is needed either What the reader will require is a passing familiarity with the basics of pure and impure functional programming for general background see BW Pau The languages refered to are Haskell HPW Miranda Tur Standard ML MTH and Scheme RC Some readers will recognise that the title of this pap er is a homage to Reynolds Rey and that the use of monads was inspired by Moggi Moga Mogb Of these matters more will b e said in the conclusion For now please note that the word essence is used in a technical sense I wish to argue that the technique describ ed in this pap er is helpful not that it is necessary The remainder of this pap er is organised as follows Section illustrates the use of monads to structure programs by considering several variations of an interpreter Section explores the relation b etween monads and continuationpassing style Section sketches how these ideas have b een applied in a compiler for Haskell that is itself written in Haskell Section concludes Miranda is a trademark of ResearchSoftware Limited Interpreting monads This section demonstrates the thesis that monads enhance mo dularityby presenting several variations of a simple interpreter for lamb da calculus The interpreter is shown in Figure It is written in Haskell The notation name expr stands for a lamb da expression and name is an inx op erator The typ e constructor M and functions unitM bindMandshowM have to do with monads and are explained b elow The interpreter deals with values and terms A value is either Wronga numb er or a function The value Wrong indicates an error suchasanunbound variable an attempt to add nonnumb ers or an attempt to apply a nonfunction A term is either a variable a constant a sum a lamb da expression or an application The following will serve as test data term App Lam x Add Var x Var x Add Con Con In more conventional notation this would b e written x x x For the standard interpreter evaluating test term yields the string The interpreter has b een kept small for ease of illustration It can easily b een extended to deal with additional values such as b o oleans pairs and lists and additional term forms such as conditional and xp oint What is a monad bindM consisting of a typ e constructor For our purp oses a monad is a triple MunitM M and a pair of p olymorphic functions unitM aMa bindM MaaMbMb These functions must satisfy three laws which are discussed in Section The basic idea in converting a program to monadic form is this a function of type abis converted to one of type aMb Thus in the denition of Valuefunc tions havetyp e Value M Value rather than Value Valueandinterp has typ e Term Environment M Value rather than typ e Term EnvironmentValue Similarly for the auxiliary functions lookup addand apply The identity function has typ e aa The corresp onding function in monadic form is unitMwhichhastyp e aMaIttakes a value into its corresp onding representation in the monad Consider the case for constants interp Con i e unitMNumi The expression Num i has typ e Value so applying unitM to it yields the corresp onding M Value as required to matchthetyp e of interp Two functions kaband h b c may b e comp osed b y writing type Name String data Term Var Name Con Int Add Term Term Lam Name Term App Term Term data Value Wrong Num Int Fun Value M Value type Environment Name Value showval Value String showval Wrong wrong showval Num i showint i showval Fun f function interp Term Environment M Value interp Var x e lookup x e interp Con i e unitM Num i interp Add u v e interp u e bindM a interp v e bindM b add a b interp Lam x v e unitM Fun a interp v xae interp App t u e interp t e bindM f interp u e bindM a apply f a lookup Name Environment M Value lookup x unitM Wrong lookup x ybe if xy then unitM b else lookup x e add Value Value M Value add Num i Num j unitM Num ij add a b unitM Wrong apply Value Value M Value apply Fun k a ka apply f a unitM Wrong test Term String test t showM interp t alue Figure Interpretation in a monad callbyv a let bk a in hb which has typ e acHerename expr is a lamb da expression By convention a will double as a typ e variable and a value variable Similarlytwo functions in monadic form k aMband hbMcare comp osed by writing a k a bindM b h b which has typ e aMcHerename is Haskell notation for an inx function The expression a name b is equivalentto name a b Thus bindM serves a role similar to a let expression The three monad laws alluded to ab ove simply insure that this form of comp osition is asso ciative and has unitM as a left and rightidentity Consider the case for sums interp Add u v e interp u e bindM a interp v e bindM b add a b This can b e read as follows evaluate ubinda to the result evaluate v bind b to the result add a to b The typ es work out the calls to interp and add yield results of typ e havetyp e Value M Value and variables a and b Application is handled similarly in particular b oth the function and its argument are evaluated so this interpreter is using a callbyvalue strategyAninterpreter with a callbyname strategy is discussed in Section Just as the typ e Value represents a value the typ e M Value can b e thoughtofas representing a computation The purp ose of unitM is to co erce a value into a computation the purp ose of bindM is to evaluate a computation yielding a
Details
-
File Typepdf
-
Upload Time-
-
Content LanguagesEnglish
-
Upload UserAnonymous/Not logged-in
-
File Pages23 Page
-
File Size-