Imperative Functional Programming

Total Page:16

File Type:pdf, Size:1020Kb

Imperative Functional Programming Imp erative functional programming Simon L Peyton Jones Philip Wadler Dept of Computing Science University of Glasgow Email simonpjwadlerdcsglagsowacuk Octob er This paper appears in ACM Symposium on Principles Of Programming Languages POPL Charleston Jan pp This copy corrects a few minor typographical errors in the published version Abstract IO are constructed by gluing together smaller pro grams that do so Section Combined with higher We present a new mo del based on monads for p erform order functions and lazy evaluation this gives a ing inputoutput in a nonstrict purely functional lan highly expressive medium in which to express IO guage It is comp osable extensible ecient requires no p erforming computations Section quite the extensions to the type system and extends smo othly to reverse of the sentiment with which we b egan this incorp orate mixedlanguage working and inplace array section up dates We compare the monadic approach to IO with other standard approaches dialogues and continuations Section and eect systems and linear types Sec Introduction tion Inputoutput has always app eared to b e one of the less It is easily extensible The key to our implementation satisfactory features of purely functional languages t is to extend Haskell with a single form that allows one ting action into the functional paradigm feels like tting to call an any pro cedure written in the programming a square blo ck into a round hole Closely related dicul language C Kernighan Ritchie without ties are asso ciated with p erforming inplace up date op er losing referential transparency Section Using ations on arrays and calling arbitrary pro cedures written it programmers can readily extend the p ower of the in some other p ossibly sideeecting language IO system by writing Haskell functions which call op erating system pro cedures Some mostlyfunctional languages such as Lisp or SML deal successfully with inputoutput by using side eects It is ecient Our Haskell compiler has C as its We fo cus on purelyfunctional solutions which rule out target co de Given a Haskell program p erforming an side eects for two reasons Firstly the absence of side IO lo op the compiler can pro duce C co de which is eects p ermits unrestricted use of equational reasoning very similar to that which one would write by hand and program transformation Secondly we are interested Section in nonstrict languages in which the order of evaluation Its eciency is achieved by applying simple pro and hence the order of any side eects is delib erately gram transformations We use unboxed data types unsp ecied laziness and side eect are fundamentally in Peyton Jones Launchbury to exp ose rep imical resentation and orderofevaluation detail to co de There is no shortage of prop osals for inputoutput in lazy improving transformations rather than relying on ad functional languages some of which we survey later but hoc optimisations in the co de generator Section no one solution has b ecome accepted as the consensus It extends uniformly to provide interleaved IO and This pap er outlines a new approach based on monads reference types Section Moggi Wadler Wadler with a num b er of noteworthy features It extends uniformly to support incremental arrays with inplace update Section Our implementa It is composable Large programs which engage in tion is ecient enough that we can dene monolithic Haskell array op erations in terms of incremental ar mainIO IO rays Hudak have prop osed a similar metho d based mainIO putcIO on continuations Our metho d is more general than This is the p oint at which b eing is converted to doing his in the following sense monads can implement when executed the putcIO action will b e p erformed and continuations but not the converse write an exclamation mark to the standard output It is based only on the Hind leyMilner type system Some other prop osals require linear types or existen Comp osing IO op erations tial types ours do es not The functions dened ab ove allow one to dene a single We have implemented all that we describ e in the con action but how can actions b e combined For example text of a compiler for Haskell Hudak et al with how can we write a program to print two exclamation the exception of the extension to arrays and reference marks To do so we introduce two glue combinators types The entire IO system provided by our compiler doneIO IO is written in Haskell using the nonstandard extensions seqIO IO a IO b IO b we describ e b elow The languages standard Dialogue interface for IO is supp orted by providing a function to The comp ound action m seqIO n is p erformed by rst convert a Dialogue into our IO monad The system is p erforming m and then p erforming n returning whatever freely available by FTP n returns as the result of the comp ound action Back We do not claim any fundamental expressiveness or e quotes are Haskells syntax for an inx op erator The ciency which is not obtainable through existing systems action doneIO do es no IO and returns the unit value except where arrays are concerned Nevertheless we feel To illustrate here is an action putsIO which puts a that the entire system works particularly smo othly as a string to the standard output whole from the standp oint of b oth programmer and im putsIO Char IO plementor putsIO doneIO putsIO aas putcIO a seqIO Overview putsIO as We need a way to reconcile being with doing an expres We can now use putsIO to dene a program which prints sion in a functional language denotes a value while an hello twice IO command should perform an action We integrate mainIO hello seqIO hello these worlds by providing a type IO a denoting actions where that when performed may do some IO and then return hello putsIO hello a value of type a The following provide simple Unix avoured IO op erations This example illustrates the distinction b etween an action and its p erformance hello is an action which happ ens to getcIO IO Char b e p erformed twice The program is precisely equivalent putcIO Char IO to one in which putsIO hello is substituted for either Here getcIO is an action which when p erformed reads a or b oth of the o ccurrences of hello In short programs character from the standard input and returns that char remain referentially transparent acter and putcIO a is an action which when p erformed In general an action may also return a value Again writes the character a to the standard output Actions there are two combinators The rst is again trivial which have nothing interesting to return such as putcIO return the empty tuple whose type is also written unitIO a IO a Notice the distinction b etween an action and its p erfor If x is of type a then unitIO x denotes the action that mance Think of an action as a script which is p er when p erformed do es nothing save return x The second formed by executing it Actions themselves are rstclass combines two actions citizens How then are actions p erformed In our sys tem the value of the entire program is a single p erhaps bindIO IO a a IO b IO b large action called mainIO and the program is executed by p erforming this action For example the following is If m IO a and k a IO b then m bindIO k a legal Haskell program denotes the action that when p erformed b ehaves as fol lows rst p erform action m yielding a value x of type easier by dening new actionmanipulating combinators a then p erform action k x yielding a value y of type b For example the denition of putsIO given ab ove uses and then return value y To illustrate here is an action explicit recursion Here is an alternative way to write that echoes the standard input to the standard output putsIO which do es not do so In Haskell x e stands for a lambda abstraction the putsIO as seqsIO map putcIO as b o dy of the abstraction extends as far as p ossible The map applies putcIO to each character in the list as to echo IO pro duce a list of actions The combinator seqsIO takes echo getcIO bindIO a a list of actions and p erforms them in sequence that is if a eof then it encapsulates the recursion It is easy to dene seqsIO doneIO thus else putcIO a seqIO seqsIO IO a IO echo seqsIO doneIO seqsIO aas a seqIO seqsIO as The combinators bindIO and unitIO are generalisations of seqIO and doneIO Here are denitions for the latter or even using the standard listpro cessing function in terms of the former foldr thus doneIO unitIO seqsIO foldr seqIO doneIO m seqIO n m bindIO a n To take another example here is a function which writes The combinators have a useful algebra doneIO and a given number of spaces to the standard output seqIO form a monoid while bindIO and unitIO form a monad Moggi Wadler Wadler spaceIO Int IO spaceIO n seqsIO take n repeat putcIO Imp erative programming The functions take and repeat are standard list It will not have escap ed the readers notice that programs pro cessing functions with nothing to do with IO from written in the monadic style lo ok rather similar to imp er Haskells standard prelude The function repeat takes a ative programs For example the echo program in C value and returns an innite list each of whose elements might lo ok something like this is the given value The function take takes a prex of given length from a list echo loop a getchara These necessarily small examples could easily b e pro if a eof grammed with explicit recursion without signicant loss return of clarity or even a gain The p oint we are making is else putchara that it is easy for the programmer to dene new glue to goto loop
Recommended publications
  • Programming Paradigms & Object-Oriented
    4.3 (Programming Paradigms & Object-Oriented- Computer Science 9608 Programming) with Majid Tahir Syllabus Content: 4.3.1 Programming paradigms Show understanding of what is meant by a programming paradigm Show understanding of the characteristics of a number of programming paradigms (low- level, imperative (procedural), object-oriented, declarative) – low-level programming Demonstrate an ability to write low-level code that uses various address modes: o immediate, direct, indirect, indexed and relative (see Section 1.4.3 and Section 3.6.2) o imperative programming- see details in Section 2.3 (procedural programming) Object-oriented programming (OOP) o demonstrate an ability to solve a problem by designing appropriate classes o demonstrate an ability to write code that demonstrates the use of classes, inheritance, polymorphism and containment (aggregation) declarative programming o demonstrate an ability to solve a problem by writing appropriate facts and rules based on supplied information o demonstrate an ability to write code that can satisfy a goal using facts and rules Programming paradigms 1 4.3 (Programming Paradigms & Object-Oriented- Computer Science 9608 Programming) with Majid Tahir Programming paradigm: A programming paradigm is a set of programming concepts and is a fundamental style of programming. Each paradigm will support a different way of thinking and problem solving. Paradigms are supported by programming language features. Some programming languages support more than one paradigm. There are many different paradigms, not all mutually exclusive. Here are just a few different paradigms. Low-level programming paradigm The features of Low-level programming languages give us the ability to manipulate the contents of memory addresses and registers directly and exploit the architecture of a given processor.
    [Show full text]
  • Structure Interpretation of Text Formats
    1 1 Structure Interpretation of Text Formats 2 3 SUMIT GULWANI, Microsoft, USA 4 VU LE, Microsoft, USA 5 6 ARJUN RADHAKRISHNA, Microsoft, USA 7 IVAN RADIČEK, Microsoft, Austria 8 MOHAMMAD RAZA, Microsoft, USA 9 Data repositories often consist of text files in a wide variety of standard formats, ad-hoc formats, aswell 10 mixtures of formats where data in one format is embedded into a different format. It is therefore a significant 11 challenge to parse these files into a structured tabular form, which is important to enable any downstream 12 data processing. 13 We present Unravel, an extensible framework for structure interpretation of ad-hoc formats. Unravel 14 can automatically, with no user input, extract tabular data from a diverse range of standard, ad-hoc and 15 mixed format files. The framework is also easily extensible to add support for previously unseen formats, 16 and also supports interactivity from the user in terms of examples to guide the system when specialized data extraction is desired. Our key insight is to allow arbitrary combination of extraction and parsing techniques 17 through a concept called partial structures. Partial structures act as a common language through which the file 18 structure can be shared and refined by different techniques. This makes Unravel more powerful than applying 19 the individual techniques in parallel or sequentially. Further, with this rule-based extensible approach, we 20 introduce the novel notion of re-interpretation where the variety of techniques supported by our system can 21 be exploited to improve accuracy while optimizing for particular quality measures or restricted environments.
    [Show full text]
  • The Marriage of Effects and Monads
    The Marriage of Effects and Monads PHILIP WADLER Avaya Labs and PETER THIEMANN Universit¨at Freiburg Gifford and others proposed an effect typing discipline to delimit the scope of computational ef- fects within a program, while Moggi and others proposed monads for much the same purpose. Here we marry effects to monads, uniting two previously separate lines of research. In partic- ular, we show that the type, region, and effect system of Talpin and Jouvelot carries over di- rectly to an analogous system for monads, including a type and effect reconstruction algorithm. The same technique should allow one to transpose any effect system into a corresponding monad system. Categories and Subject Descriptors: D.3.1 [Programming Languages]: Formal Definitions and Theory; F.3.2 [Logics and Meanings of Programs]: Semantics of Programming Languages— Operational semantics General Terms: Languages, Theory Additional Key Words and Phrases: Monad, effect, type, region, type reconstruction 1. INTRODUCTION Computational effects, such as state or continuations, are powerful medicine. If taken as directed they may cure a nasty bug, but one must be wary of the side effects. For this reason, many researchers in computing seek to exploit the benefits of computational effects while delimiting their scope. Two such lines of research are the effect typing discipline, proposed by Gifford and Lucassen [Gifford and Lucassen 1986; Lucassen 1987], and pursued by Talpin and Jouvelot [Talpin and Jouvelot 1992, 1994; Talpin 1993] among others, and the use of monads, proposed by Moggi [1989, 1990], and pursued by Wadler [1990, 1992, 1993, 1995] among others. Effect systems are typically found in strict languages, such as FX [Gifford et al.
    [Show full text]
  • Exploring Languages with Interpreters and Functional Programming Chapter 8
    Exploring Languages with Interpreters and Functional Programming Chapter 8 H. Conrad Cunningham 24 September 2018 Contents 8 Evaluation Model 2 8.1 Chapter Introduction . .2 8.2 Referential Transparency Revisited . .2 8.3 Substitution Model . .3 8.4 Time and Space Complexity . .6 8.5 Termination . .7 8.6 What Next? . .7 8.7 Exercises . .8 8.8 Acknowledgements . .8 8.9 References . .9 8.10 Terms and Concepts . .9 Copyright (C) 2016, 2017, 2018, H. Conrad Cunningham Professor of Computer and Information Science University of Mississippi 211 Weir Hall P.O. Box 1848 University, MS 38677 (662) 915-5358 Browser Advisory: The HTML version of this textbook requires a browser that supports the display of MathML. A good choice as of September 2018 is a recent version of Firefox from Mozilla. 1 8 Evaluation Model 8.1 Chapter Introduction This chapter introduces an evaluation model applicable to Haskell programs. As in the previous chapters, this chapter focuses on use of first-order functions and primitive data types. A goal of this chapter and the next one is enable students to analyze Haskell functions to determine under what conditions they terminate normally and how efficient they are. This chapter presents the evaluation model and the next chapter informally analyzes simple functions in terms of time and space efficiency and termination. How can we evaluate (i.e. execute) an expression that “calls” a function like the fact1 function from Chapter 4? We do this by rewriting expressions using a substitution model, as we see in this chapter. This process depends upon a property of functional languages called referential transparency.
    [Show full text]
  • 15-150 Lectures 27 and 28: Imperative Programming
    15-150 Lectures 27 and 28: Imperative Programming Lectures by Dan Licata April 24 and 26, 2012 In these lectures, we will show that imperative programming is a special case of functional programming. We will also investigate the relationship between imperative programming and par- allelism, and think about what happens when the two are combined. 1 Mutable Cells Functional programming is all about transforming data into new data. Imperative programming is all about updating and changing data. To get started with imperative programming, ML provides a type 'a ref representing mutable memory cells. This type is equipped with: • A constructor ref : 'a -> 'a ref. Evaluating ref v creates and returns a new memory cell containing the value v. Pattern-matching a cell with the pattern ref p gets the contents. • An operation := : 'a ref * 'a -> unit that updates the contents of a cell. For example: val account = ref 100 val (ref cur) = account val () = account := 400 val (ref cur) = account 1. In the first line, evaluating ref 100 creates a new memory cell containing the value 100, which we will write as a box: 100 and binds the variable account to this cell. 2. The next line pattern-matches account as ref cur, which binds cur to the value currently in the box, in this case 100. 3. The next line updates the box to contain the value 400. 4. The final line reads the current value in the box, in this case 400. 1 It's important to note that, with mutation, the same program can have different results if it is evaluated multiple times.
    [Show full text]
  • Week 3: Scope and Evaluation Order Assignment 1 Has Been Posted!
    Week 3: Scope and Evaluation Order CSC324 Principles of Programming Languages David Liu, Department of Computer Science Assignment 1 has been posted! Closures and static scope static (adjective) determined only by the program source code dynamic (adjective) determined only when the program is run E.g., referential transparency is a static property How are closures implemented? Are they static or dynamic? Or both? Function bodies can be processed statically (e.g., Haskell compiler generates code once per lambda). The closure environment (and therefore the closure itself) can only be generated dynamically. The closure depends only on where the function is evaluated, not where that function is called. (define (make-adder n) (lambda (x) (+ x n))) (define adder (make-adder 1)) (adder 100) So we can determine where each free identifier obtains its values statically, based on where its enclosing function is defined. scope (of an identifier) The parts of program code that may refer to that identifier. static (aka lexical) scope The scope of every identifier is determined by the structure of the source code (e.g., by nesting of lambdas and lets). Every identifier obtains its value from the closest enclosing expression that binds it. (define (make-adder n) (lambda (x) (+ x n))) (define adder (make-adder 1)) ; (0x..., {n: 1}) (let* ([n 100]) (adder 2)) Implementing static scope in an interpreter A simple interpreter (define/match (interpret env expr) [(_ (? number?)) expr] [(_ (? symbol?)) (hash-ref env expr)] [(_ (list '+ l r)) (+ (interpret env l) (interpret env r))]) A simple interpreter (define/match (interpret env expr) [(_ (? number?)) expr] [(_ (? symbol?)) (hash-ref env expr)] [(_ (list '+ l r)) (+ (interpret env l) (interpret env r))]) The environment is passed recursively when interpreting each subexpression.
    [Show full text]
  • Functional and Imperative Object-Oriented Programming in Theory and Practice
    Uppsala universitet Inst. för informatik och media Functional and Imperative Object-Oriented Programming in Theory and Practice A Study of Online Discussions in the Programming Community Per Jernlund & Martin Stenberg Kurs: Examensarbete Nivå: C Termin: VT-19 Datum: 14-06-2019 Abstract Functional programming (FP) has progressively become more prevalent and techniques from the FP paradigm has been implemented in many different Imperative object-oriented programming (OOP) languages. However, there is no indication that OOP is going out of style. Nevertheless the increased popularity in FP has sparked new discussions across the Internet between the FP and OOP communities regarding a multitude of related aspects. These discussions could provide insights into the questions and challenges faced by programmers today. This thesis investigates these online discussions in a small and contemporary scale in order to identify the most discussed aspect of FP and OOP. Once identified the statements and claims made by various discussion participants were selected and compared to literature relating to the aspects and the theory behind the paradigms in order to determine whether there was any discrepancies between practitioners and theory. It was done in order to investigate whether the practitioners had different ideas in the form of best practices that could influence theories. The most discussed aspect within FP and OOP was immutability and state relating primarily to the aspects of concurrency and performance. ​ ​ ​ ​ ​ ​ This thesis presents a selection of representative quotes that illustrate the different points of view held by groups in the community and then addresses those claims by investigating what is said in literature.
    [Show full text]
  • Unit 2 — Imperative and Object-Oriented Paradigm
    Programming Paradigms Unit 2 — Imperative and Object-oriented Paradigm J. Gamper Free University of Bozen-Bolzano Faculty of Computer Science IDSE PP 2018/19 Unit 2 – Imperative and Object-oriented Paradigm 1/38 Outline 1 Imperative Programming Paradigm 2 Abstract Data Types 3 Object-oriented Approach PP 2018/19 Unit 2 – Imperative and Object-oriented Paradigm 2/38 Imperative Programming Paradigm Outline 1 Imperative Programming Paradigm 2 Abstract Data Types 3 Object-oriented Approach PP 2018/19 Unit 2 – Imperative and Object-oriented Paradigm 3/38 Imperative Programming Paradigm Imperative Paradigm/1 The imperative paradigm is the oldest and most popular paradigm Based on the von Neumann architecture of computers Imperative programs define sequences of commands/statements for the computer that change a program state (i.e., set of variables) Commands are stored in memory and executed in the order found Commands retrieve data, perform a computation, and assign the result to a memory location Data ←→ Memory CPU (Data and Address Program) ←→ The hardware implementation of almost all Machine code computers is imperative 8B542408 83FA0077 06B80000 Machine code, which is native to the C9010000 008D0419 83FA0376 computer, and written in the imperative style B84AEBF1 5BC3 PP 2018/19 Unit 2 – Imperative and Object-oriented Paradigm 4/38 Imperative Programming Paradigm Imperative Paradigm/2 Central elements of imperative paradigm: Assigment statement: assigns values to memory locations and changes the current state of a program Variables refer
    [Show full text]
  • Pattern Matching
    Functional Programming Steven Lau March 2015 before function programming... https://www.youtube.com/watch?v=92WHN-pAFCs Models of computation ● Turing machine ○ invented by Alan Turing in 1936 ● Lambda calculus ○ invented by Alonzo Church in 1930 ● more... Turing machine ● A machine operates on an infinite tape (memory) and execute a program stored ● It may ○ read a symbol ○ write a symbol ○ move to the left cell ○ move to the right cell ○ change the machine’s state ○ halt Turing machine Have some fun http://www.google.com/logos/2012/turing-doodle-static.html http://www.ioi2012.org/wp-content/uploads/2011/12/Odometer.pdf http://wcipeg.com/problems/desc/ioi1211 Turing machine incrementer state symbol action next_state _____ state 0 __1__ state 1 0 _ or 0 write 1 1 _10__ state 2 __1__ state 1 0 1 write 0 2 _10__ state 0 __1__ state 0 _00__ state 2 1 _ left 0 __0__ state 2 _00__ state 0 __0__ state 0 1 0 or 1 right 1 100__ state 1 _10__ state 1 2 0 left 0 100__ state 1 _10__ state 1 100__ state 1 _10__ state 1 100__ state 1 _10__ state 0 100__ state 0 _11__ state 1 101__ state 1 _11__ state 1 101__ state 1 _11__ state 0 101__ state 0 λ-calculus Beware! ● think mathematical, not C++/Pascal ● (parentheses) are for grouping ● variables cannot be mutated ○ x = 1 OK ○ x = 2 NO ○ x = x + 1 NO λ-calculus Simplification 1 of 2: ● Only anonymous functions are used ○ f(x) = x2+1 f(1) = 12+1 = 2 is written as ○ (λx.x2+1)(1) = 12+1 = 2 note that f = λx.x2+1 λ-calculus Simplification 2 of 2: ● Only unary functions are used ○ a binary function can be written as a unary function that return another unary function ○ (λ(x,y).x+y)(1,2) = 1+2 = 3 is written as [(λx.(λy.x+y))(1)](2) = [(λy.1+y)](2) = 1+2 = 3 ○ this technique is known as Currying Haskell Curry λ-calculus ● A lambda term has 3 forms: ○ x ○ λx.A ○ AB where x is a variable, A and B are lambda terms.
    [Show full text]
  • The Power of Higher-Order Composition Languages in System Design
    The Power of Higher-Order Composition Languages in System Design James Adam Cataldo Electrical Engineering and Computer Sciences University of California at Berkeley Technical Report No. UCB/EECS-2006-189 http://www.eecs.berkeley.edu/Pubs/TechRpts/2006/EECS-2006-189.html December 18, 2006 Copyright © 2006, by the author(s). All rights reserved. Permission to make digital or hard copies of all or part of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commercial advantage and that copies bear this notice and the full citation on the first page. To copy otherwise, to republish, to post on servers or to redistribute to lists, requires prior specific permission. The Power of Higher-Order Composition Languages in System Design by James Adam Cataldo B.S. (Washington University in St. Louis) 2001 M.S. (University of California, Berkeley) 2003 A dissertation submitted in partial satisfaction of the requirements for the degree of Doctor of Philosophy in Electrical Engineering in the GRADUATE DIVISION of the UNIVERSITY OF CALIFORNIA, BERKELEY Committee in charge: Professor Edward Lee, Chair Professor Alberto Sangiovanni-Vincentelli Professor Raja Sengupta Fall 2006 The dissertation of James Adam Cataldo is approved: Chair Date Date Date University of California, Berkeley Fall 2006 The Power of Higher-Order Composition Languages in System Design Copyright 2006 by James Adam Cataldo 1 Abstract The Power of Higher-Order Composition Languages in System Design by James Adam Cataldo Doctor of Philosophy in Electrical Engineering University of California, Berkeley Professor Edward Lee, Chair This dissertation shows the power of higher-order composition languages in system design.
    [Show full text]
  • A Critique of Abelson and Sussman Why Calculating Is Better Than
    A critique of Abelson and Sussman - or - Why calculating is better than scheming Philip Wadler Programming Research Group 11 Keble Road Oxford, OX1 3QD Abelson and Sussman is taught [Abelson and Sussman 1985a, b]. Instead of emphasizing a particular programming language, they emphasize standard engineering techniques as they apply to programming. Still, their textbook is intimately tied to the Scheme dialect of Lisp. I believe that the same approach used in their text, if applied to a language such as KRC or Miranda, would result in an even better introduction to programming as an engineering discipline. My belief has strengthened as my experience in teaching with Scheme and with KRC has increased. - This paper contrasts teaching in Scheme to teaching in KRC and Miranda, particularly with reference to Abelson and Sussman's text. Scheme is a "~dly-scoped dialect of Lisp [Steele and Sussman 19781; languages in a similar style are T [Rees and Adams 19821 and Common Lisp [Steele 19821. KRC is a functional language in an equational style [Turner 19811; its successor is Miranda [Turner 1985k languages in a similar style are SASL [Turner 1976, Richards 19841 LML [Augustsson 19841, and Orwell [Wadler 1984bl. (Only readers who know that KRC stands for "Kent Recursive Calculator" will have understood the title of this There are four language features absent in Scheme and present in KRC/Miranda that are important: 1. Pattern-matching. 2. A syntax close to traditional mathematical notation. 3. A static type discipline and user-defined types. 4. Lazy evaluation. KRC and SASL do not have a type discipline, so point 3 applies only to Miranda, Philip Wadhr Why Calculating is Better than Scheming 2 b LML,and Orwell.
    [Show full text]
  • SI 413, Unit 3: Advanced Scheme
    SI 413, Unit 3: Advanced Scheme Daniel S. Roche ([email protected]) Fall 2018 1 Pure Functional Programming Readings for this section: PLP, Sections 10.7 and 10.8 Remember there are two important characteristics of a “pure” functional programming language: • Referential Transparency. This fancy term just means that, for any expression in our program, the result of evaluating it will always be the same. In fact, any referentially transparent expression could be replaced with its value (that is, the result of evaluating it) without changing the program whatsoever. Notice that imperative programming is about as far away from this as possible. For example, consider the C++ for loop: for ( int i = 0; i < 10;++i) { /∗ some s t u f f ∗/ } What can we say about the “stuff” in the body of the loop? Well, it had better not be referentially transparent. If it is, then there’s no point in running over it 10 times! • Functions are First Class. Another way of saying this is that functions are data, just like any number or list. Functions are values, in fact! The specific privileges that a function earns by virtue of being first class include: 1) Functions can be given names. This is not a big deal; we can name functions in pretty much every programming language. In Scheme this just means we can do (define (f x) (∗ x 3 ) ) 2) Functions can be arguments to other functions. This is what you started to get into at the end of Lab 2. For starters, there’s the basic predicate procedure?: (procedure? +) ; #t (procedure? 10) ; #f (procedure? procedure?) ; #t 1 And then there are “higher-order functions” like map and apply: (apply max (list 5 3 10 4)) ; 10 (map sqrt (list 16 9 64)) ; '(4 3 8) What makes the functions “higher-order” is that one of their arguments is itself another function.
    [Show full text]