Introducing Elixir Getting Started in Functional Programming [St. Laurent & Eisenberg 2014-09-25].Pdf
Total Page:16
File Type:pdf, Size:1020Kb
Introducing Elixir Introducing Elixir Introducing Elixir is an excellent language if you want to learn about functional programming, and with this hands-on introduction, you’ll discover just how powerful and fun Elixir can be. This language combines the robust functional programming of Erlang with a syntax similar to Ruby, and includes powerful features for metaprogramming. This book shows you how to write simple Elixir programs by teaching one skill at a time. Once you pick up pattern matching, process-oriented programming, and other concepts, you’ll understand why Elixir makes it easier to build concurrent and resilient programs that scale up and down with ease. ■ Get comfortable with IEx, Elixir’s command-line interface ■ Discover atoms, pattern matching, and guards: the foundations of your program structure ■ Delve into the heart of Elixir with recursion, strings, lists, and higher-order functions ■ Create processes, send messages among them, and apply pattern matching to incoming messages ■ Store and manipulate structured data with Erlang Term Storage and the Mnesia database ■ Build resilient applications with Erlang’s Open Telecom Platform Introducing ■ Define macros with Elixir’s metaprogramming tools St. Laurent & Eisenberg Laurent St. Simon St. Laurent is a Strategic Content Director at O’Reilly Media, Inc., focusing primarily on web-related topics. He is co-chair of O’Reilly’s Fluent and OSCON conferences. Simon has written or co-written books, including Introducing Erlang, Learning Rails 3, and XML Pocket Reference, Third Edition (all O’Reilly). J. David Eisenberg is a programmer and instructor in San Jose, California, with a talent for teaching and explaining. He’s developed courses for CSS, JavaScript, CGI, and XML, and teaches Computer Information Technology courses at Evergreen Valley College. David has written books including SVG Essentials, Études for Erlang (both O’Reilly), and Let’s Read Hiragana (Eisenberg Consulting). Elixir GETTING STARTED IN FUNCTIONAL PROGRAMMING PROGRAMMING LANGUAGES Twitter: @oreillymedia facebook.com/oreilly US $24.99 CAN $26.99 ISBN: 978-1-449-36999-6 Simon St. Laurent & J. David Eisenberg www.it-ebooks.info Introducing Elixir Introducing Elixir Introducing Elixir is an excellent language if you want to learn about functional programming, and with this hands-on introduction, you’ll discover just how powerful and fun Elixir can be. This language combines the robust functional programming of Erlang with a syntax similar to Ruby, and includes powerful features for metaprogramming. This book shows you how to write simple Elixir programs by teaching one skill at a time. Once you pick up pattern matching, process-oriented programming, and other concepts, you’ll understand why Elixir makes it easier to build concurrent and resilient programs that scale up and down with ease. ■ Get comfortable with IEx, Elixir’s command-line interface ■ Discover atoms, pattern matching, and guards: the foundations of your program structure ■ Delve into the heart of Elixir with recursion, strings, lists, and higher-order functions ■ Create processes, send messages among them, and apply pattern matching to incoming messages ■ Store and manipulate structured data with Erlang Term Storage and the Mnesia database ■ Build resilient applications with Erlang’s Open Telecom Platform Introducing ■ Define macros with Elixir’s metaprogramming tools St. Laurent & Eisenberg Laurent St. Simon St. Laurent is a Strategic Content Director at O’Reilly Media, Inc., focusing primarily on web-related topics. He is co-chair of O’Reilly’s Fluent and OSCON conferences. Simon has written or co-written books, including Introducing Erlang, Learning Rails 3, and XML Pocket Reference, Third Edition (all O’Reilly). J. David Eisenberg is a programmer and instructor in San Jose, California, with a talent for teaching and explaining. He’s developed courses for CSS, JavaScript, CGI, and XML, and teaches Computer Information Technology courses at Evergreen Valley College. David has written books including SVG Essentials, Études for Erlang (both O’Reilly), and Let’s Read Hiragana (Eisenberg Consulting). Elixir GETTING STARTED IN FUNCTIONAL PROGRAMMING PROGRAMMING LANGUAGES Twitter: @oreillymedia facebook.com/oreilly US $24.99 CAN $26.99 ISBN: 978-1-449-36999-6 Simon St. Laurent & J. David Eisenberg www.it-ebooks.info Introducing Elixir Simon St. Laurent and J. David Eisenberg www.it-ebooks.info Introducing Elixir by Simon St. Laurent and J. David Eisenberg Copyright © 2014 Simon St. Laurent and J. David Eisenberg. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://safaribooksonline.com). For more information, contact our corporate/ institutional sales department: 800-998-9938 or [email protected]. Editors: Simon St. Laurent and Meghan Blanchette Cover Designer: Karen Montgomery Production Editor: Melanie Yarbrough Interior Designer: David Futato Proofreader: Amanda Kersey Illustrator: Rebecca Demarest Indexer: J. David Eisenberg September 2014: First Edition Revision History for the First Edition: 2014-09-10: First release See http://oreilly.com/catalog/errata.csp?isbn=9781449369996 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Introducing Elixir, the cover image of a four-horned antelope, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. While the publisher and the authors have used good faith efforts to ensure that the information and in‐ structions contained in this work are accurate, the publisher and the authors disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights. ISBN: 978-1-449-36999-6 [LSI] www.it-ebooks.info Table of Contents Preface. vii 1. Getting Comfortable. 1 Installation 1 Installing Erlang 1 Installing Elixir 2 Firing It Up 2 First Steps 2 Moving Through Text and History 3 Moving Through Files 3 Doing Something 4 Calling Functions 5 Numbers in Elixir 6 Working with Variables in the Shell 8 2. Functions and Modules. 11 Fun with fn 11 And the & 13 Defining Modules 13 From Module to Free-Floating Function 16 Splitting Code Across Modules 17 Combining Functions with the Pipe Operator 18 Importing Functions 19 Default Values for Arguments 20 Documenting Code 21 Documenting Functions 22 Documenting Modules 23 iii www.it-ebooks.info 3. Atoms, Tuples, and Pattern Matching. 25 Atoms 25 Pattern Matching with Atoms 25 Atomic Booleans 27 Guards 28 Underscoring That You Don’t Care 31 Adding Structure: Tuples 33 Pattern Matching with Tuples 33 Processing Tuples 34 4. Logic and Recursion. 37 Logic Inside of Functions 37 Evaluating Cases 37 Adjusting to Conditions 40 If, or else 41 Variable Assignment in case and if Constructs 42 The Gentlest Side Effect: IO.puts 43 Simple Recursion 44 Counting Down 45 Counting Up 46 Recursing with Return Values 47 5. Communicating with Humans. 51 Strings 51 Multiline Strings 53 Unicode 54 Character Lists 54 String Sigils 55 Asking Users for Information 56 Gathering Characters 56 Reading Lines of Text 58 6. Lists. 61 List Basics 61 Splitting Lists into Heads and Tails 63 Processing List Content 64 Creating Lists with Heads and Tails 66 Mixing Lists and Tuples 68 Building a List of Lists 68 7. Name-Value Pairs. 73 Keyword Lists 73 iv | Table of Contents www.it-ebooks.info Lists of Tuples with Multiple Keys 75 Hash Dictionaries 76 From Lists to Maps 77 Creating Maps 77 Updating Maps 78 Reading Maps 78 From Maps to Structs 78 Setting Up Structs 79 Creating and Reading Structs 79 Pattern Matching Against Structs 80 Using Structs in Functions 80 Adding Behavior to Structs 82 Adding to Existing Protocols 84 8. Higher-Order Functions and List Comprehensions. 87 Simple Higher-Order Functions 87 Creating New Lists with Higher-Order Functions 89 Reporting on a List 90 Running List Values Through a Function 90 Filtering List Values 91 Beyond List Comprehensions 92 Testing Lists 92 Splitting Lists 93 Folding Lists 94 9. Playing with Processes. 97 The Shell Is a Process 97 Spawning Processes from Modules 99 Lightweight Processes 102 Registering a Process 102 When Processes Break 104 Processes Talking Amongst Themselves 105 Watching Your Processes 107 Watching Messages Among Processes 109 Breaking Things and Linking Processes 110 10. Exceptions, Errors, and Debugging. 119 Flavors of Errors 119 Rescuing Code from Runtime Errors as They Happen 120 Logging Progress and Failure 122 Tracing Messages 123 Watching Function Calls 125 Table of Contents | v www.it-ebooks.info Writing Unit Tests 126 11. Storing Structured Data. 131 Records: Structured Data Before structs 131 Setting Up Records 132 Creating and Reading Records 133 Using Records in Functions 134 Storing Data in Erlang Term Storage 136 Creating and Populating a Table 138 Simple Queries 142 Overwriting Values 143 ETS Tables and Processes 144 Next Steps 146 Storing Records in Mnesia 146 Starting up Mnesia 146 Creating Tables 147 Reading Data 151 12. Getting Started with OTP. 153 Creating Services with gen_server 154 A Simple Supervisor 159 Packaging an Application with Mix 162 13. Using Macros to Extend Elixir. 167 Functions versus Macros 167 A Simple Macro 168 Creating New Logic 170 Creating Functions Programatically 171 When (Not) to Use Macros 173 Sharing the Gospel of Elixir 173 A.