Quick Functional Programming (David Matuszek) (Z-Library)
Author: David Matuszek
技术
No Description
📄 File Format:
PDF
💾 File Size:
8.8 MB
362
Views
124
Downloads
0.00
Total Donations
📄 Text Preview (First 20 pages)
ℹ️
Registered users can read the full content for free
Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.
📄 Page
1
(This page has no text content)
📄 Page
2
Why learn functional programming? Isn’t that some compli- cated ivory- tower technique used only in obscure languages like Haskell? In fact, functional programming is actually very simple. It’s also very powerful, as Haskell demonstrates by throwing away all the conventional programming tools and using only functional pro- gramming features. But it doesn’t have to be done that way. Functional programming is a power tool that you can use in addi- tion to all your usual tools, to whatever extent your current main- stream language supports it. Most languages have at least basic support. In this book, we use Python and Java and, as a bonus, Scala. If you prefer another language, there will be minor differences in syntax, but the concepts are the same. Give functional programming a try. You may be surprised how much a single power tool can help you in your day- to- day programming. Quick Functional Programming
📄 Page
3
(This page has no text content)
📄 Page
4
Quick Functional Programming David Matuszek
📄 Page
5
First edition published 2023 by CRC Press 6000 Broken Sound Parkway NW, Suite 300, Boca Raton, FL 33487-2742 and by CRC Press 4 Park Square, Milton Park, Abingdon, Oxon, OX14 4RN CRC Press is an imprint of Taylor & Francis Group, LLC © 2023 David Matuszek Reasonable efforts have been made to publish reliable data and information, but the author and publisher cannot assume responsibility for the validity of all materials or the consequences of their use. The authors and publishers have attempted to trace the copyright holders of all material reproduced in this publication and apologize to copyright holders if permission to publish in this form has not been obtained. If any copyright material has not been acknowledged please write and let us know so we may rectify in any future reprint. Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced, transmitted, or utilized in any form by any electronic, mechanical, or other means, now known or hereafter invented, including photocopying, microfilming, and recording, or in any information storage or retrieval system, without written permission from the publishers. For permission to photocopy or use material electronically from this work, access www.copyright.com or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA 01923, 978-750-8400. For works that are not available on CCC please contact mpkbookspermissions@tandf. co.uk Trademark notice: Product or corporate names may be trademarks or registered trademarks and are used only for identification and explanation without intent to infringe. ISBN: 978-1-032-41532-1 (hbk) ISBN: 978-1-032-41531-4 (pbk) ISBN: 978-1-003-35854-1 (ebk) DOI: 10.1201/9781003358541 Typeset in Minion by SPi Technologies India Pvt Ltd (Straive)
📄 Page
6
To all my students, past, present, and future.
📄 Page
7
(This page has no text content)
📄 Page
8
vii Contents About the Author, xi Preface, xiii Chapter 1 ◾ What Is Functional Programming? 1 Chapter 2 ◾ Methods and Functions 5 2.1 Methods 6 2.1.1 Methods in Python 6 2.1.2 Methods in Java 7 2.1.3 Methods in Scala 9 2.2 Function Literals 10 2.2.1 Function Literals in Python 11 2.2.2 Function Literals in Java 12 2.2.3 Function Literals in Scala 13 2.3 Sorting Examples 14 2.3.1 Sorting in Python 14 2.3.2 Sorting in Java 16 2.3.3 Sorting in Scala 18
📄 Page
9
viii ◾ Contents Chapter 3 ◾ Higher-Order Functions 21 3.1 Higher-Order Functions in Python 22 3.2 Higher-Order Functions in Java 25 3.3 Higher-Order Functions in Scala 27 Chapter 4 ◾ Functional Interfaces in Java 31 4.1 Single Abstract Methods 31 4.2 Anonymous Inner Classes 32 4.3 Defining Functional Interfaces 33 4.4 Method References 34 4.5 The Other Method Reference 37 4.6 Provided Functional Interfaces 38 4.6.1 IntPredicate 38 4.6.2 Function Composition 39 4.6.3 Predicates Again 41 4.6.4 Unary Operators 42 4.6.5 More Functions and Operators 43 4.6.6 Suppliers and Consumers 44 Chapter 5 ◾ If Expressions 47 5.1 If Expressions in Python 47 5.2 If Expressions in Java 48 5.3 If Expressions in Scala 49 Chapter 6 ◾ Comprehensions 51 6.1 List Comprehensions in Python 52 6.2 Comprehensions in Java 54 6.3 For Expressions in Scala 54 6.4 For Comprehensions in Scala 57
📄 Page
10
Contents ◾ ix Chapter 7 ◾ Closures 59 7.1 Closures in Python 60 7.2 Closures in Java 61 7.3 Closures in Scala 63 7.4 Closure Example 64 Chapter 8 ◾ Currying 67 8.1 Currying in Python 69 8.2 Currying in Java 71 8.3 Currying in Scala 72 Chapter 9 ◾ Function Composition 75 9.1 Function Composition in Python 75 9.2 Function Composition in Java 77 9.3 Function Composition in Scala 78 Chapter 10 ◾ Optional Values 79 10.1 Optional in Python 80 10.2 Optional in Java 80 10.3 Option in Scala 81 Chapter 11 ◾ Lists 83 11.1 Recursion 84 11.2 Lists in Python 86 11.3 Lists in Java 87 11.4 Lists in Scala 87 Chapter 12 ◾ Streams 91 12.1 Generators in Python 92 12.2 Streams in Java 92
📄 Page
11
x ◾ Contents 12.3 Numeric Streams in Java 95 12.4 Streams in Scala 95 Chapter 13 ◾ Important Functions 97 13.1 Important Functions in Python 98 13.2 Important Functions in Java 99 13.3 Important Functions in Scala 102 13.4 Additional Functions in Scala 105 Chapter 14 ◾ Pipelines 107 14.1 Pipelines in Python 109 14.2 Pipelines in Java 110 14.2.1 Intermediate Operations 110 14.2.2 Terminal Operations 112 14.2.3 Collectors 114 14.2.4 Example 115 14.3 Pipelines in Scala 116 Chapter 15 ◾ Summary and Final Examples 119 15.1 Examples in Python 120 15.2 Examples in Java 122 15.3 Examples in Scala 123 Afterword 125 Index, 127
📄 Page
12
xi About the Author I’m David Matuszek, known to most of my students as “Dr. Dave.” I wrote my first program on punched cards in 1963 and immedi- ately got hooked. I taught my first computer classes in 1970, as a graduate student in Computer Science at The University of Texas in Austin. I eventu- ally got my PhD from there, and I’ve been teaching ever since. Admittedly, I spent over a dozen years in industry, but even then, I taught as an adjunct for Villanova university. I finally escaped from industry and joined the Villanova faculty full time for a few years and then moved to the University of Pennsylvania, where I directed a Master’s program (MCIT, Masters in Computer and Information Technology) for students coming into computer science from another discipline. Throughout my career, my main interests have been in artificial intelligence (AI) and programming languages. I’ve used a lot of programming languages. I retired in 2017, but I can’t stop teaching, so I’m writing a series of “quick start” books on programming and programming
📄 Page
13
xii ◾ About the Author languages. I’ve also written two science fiction novels, Ice Jockey and All True Value, and I expect to write more. Check them out! And hey, if you’re a former student of mine, drop me a note. I’d love to hear from you! david.matuszek@gmail.com
📄 Page
14
xiii Preface You probably think that functional programming (FP) is something dreamed up by ivory- tower academics using obscure languages that few people understand. You’re right. You probably think that those weird languages such as Haskell, Standard ML, and OCaml are never going to be very popular with ordinary programmers. Right again. But did you notice… • That ivory- tower academics are some pretty smart people? • That the programming language you use every day, what- ever it is, is getting more FP features? “Pure” functional programming, abandoning all the conventional programming techniques, really is difficult. But you don’t have to do that. Think of it this way: Conventional programming consists of a collection of hand tools, and FP adds a power tool to the mix. Just one—it doesn’t do everything, and you still need all the other tools (unless you’re an ivory- tower academic), but where you can use it, it saves a lot of work.
📄 Page
15
xiv ◾ Preface Here’s a spoiler: FP will let you replace many of your loops with shorter, simpler, easier to understand function calls. Yes, there’s some unfamiliar syntax involved, but it’s just syntax, and you can get used to it very quickly. The new concepts, the parts you might think are the most difficult, turn out to be trivially simple. You may be surprised how much a single power tool can help you in your day- to- day programming. FP is coming into prominence now because it is a far better way to write concurrent programs, suitable for multi- core computers. However, this is only a book about functional programming, not about concurrent programming; that would require a far larger volume. Each chapter after the first begins with an explanation of some particular concept of functional programming. After that, there are sections exemplifying that concept in each of three languages. • Python, because it is a simple, widely known language. Python has only a few of the most basic FP features. • Java, because it is widely known and has many of the FP features. The developers of these features have done an awesome job in fitting these features into a language that was never designed to hold them. • Scala, which has been designed from the ground up to be both object oriented and functional, and therefore provides the cleanest and most complete set of FP features. I have tried to make this book accessible to programmers who do not know Python or Scala. The FP features of these languages can be understood without an in- depth knowledge of the language in which they occur. Unfortunately, no such claim can be made for Java.
📄 Page
16
1DOI: 10.1201/9781003358541-1 A mathematical function has arguments, and from those arguments, it computes a result. Given the same arguments again, it will produce the same result, every time. Consequently, • A function uses its arguments, and only its arguments, to produce a result. It has no access to “global variables,” ran- dom numbers, the time of day, or anything like that. • A function has no side effects. It does not change anything in its environment. It does not change the values of its arguments. It does no input or output. • A function has referential transparency. Once the value of a function with certain arguments has been computed, then any call to the function with those arguments, in any context, may be replaced by that value. A function with the above characteristics is called a pure function. C H A P T E R 1 What Is Functional Programming?
📄 Page
17
2 ◾ Quick Functional Programming In a functional language, functions are values. This means that they can be stored in variables, passed around as parameters, and returned as the result of a function calls, just like any other type of value. There are even operations on functions that produce new functions. Almost any programming language has functions, of course, but in functional programming, the entire program is thought of as being a function that has functions within it. Obviously, programs need the ability to do input and output. One reason purely functional languages such as Haskell are difficult is that they require input/output to be put in a “walled garden” where they don’t have to be seen by the rest of the code. The ability of Haskell to do this is something of an intellectual feat, but its practical value is controversial. Another important idea from mathematics is that variables don’t vary. If the value of a variable x is known, it has the same value throughout the computation. If you want to model a process that changes over time, you might say x' = f(x), where x' is a “new” value; but it is also in a new variable, x'. To model this in programming terms, we say that variables have to be single assignment—once given a value, that value cannot be changed. In addition, that value must be immutable; for example, it cannot be an array whose elements can be changed. The single-assignment property means that we need some way to create new variables; not only x but also x', x'', x''', and so on for as many variables as we need. This is easily done with recursion, because every recursive call creates a new set of variables. Loops, on the other hand, are used almost exclusively to change values, which is contrary to the functional programming view. Because any task that can be accomplished with loops can also be done with recur- sion, functional programming uses recursion rather than loops.
📄 Page
18
What Is Functional Programming? ◾ 3 Because values must be immutable, memory demands for new values can be high. This is dealt with by automatically garbage collecting values that are no longer needed and by using persis- tent data structures: A change to one part of the data structure does not require making a complete copy of the parts that have not changed. Another consequence is that functional programming is expres- sion-oriented rather than statement-oriented. An entire program may consist of a single expression, along with definitions of vari- ables and functions (which themselves consist of single expressions). In summary, pure functional programming requires that: • Functions are pure and can be treated as values. • Variables are single-assignment, and values are immutable. • Recursion is used in preference to loops. • Garbage collection is automatic and data structures are persistent. • Programs are expression-oriented rather than statement- oriented. Pure functional programming can be done in specialized lan- guages such as Haskell and OCaml. For the practicing pro- grammer, however, such purity is unattainable in conventional languages. This is not without its advantages; all the usual pro- gramming tools, including loops, can be employed, while also making use of functional programming features when they are appropriate. The reader may question why a less common language such as Scala is included in this book. Python supports only the most
📄 Page
19
4 ◾ Quick Functional Programming basic functional features; Java supports more features, but at the cost of considerable added complexity; and purely functional lan- guages such as Haskell seem downright “weird” to most pro- grammers. Scala has an almost complete set of functional programming features, but the syntax is much closer to that of mainstream languages, so the Scala examples should be fairly easy to understand.
📄 Page
20
5DOI: 10.1201/9781003358541-2 A method belongs to an object. It has access to the fields of the object and can read and modify them. It can use other methods in that object. A function is, or should be, independent of the context in which it occurs. It should use only its arguments in computing a result; it should have no side effects; and it should have referential transparency. Of course, not all methods access the fields or call other meth- ods of the object that owns them, and not all functions are “pure” in the above sense. One of the chief advantages of pure functions is that their cor- rectness can be verified without taking context into account. This makes pure functions much easier to debug. Another advantage is that, since pure functions do not depend on con- text, they can be passed around as freely as any other kind of value. C H A P T E R 2 Methods and Functions
The above is a preview of the first 20 pages. Register to read the complete e-book.