Introducing Elixir Introducing Elixir 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 ■■ Define macros with Elixir’s metaprogramming tools Introducing 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) PROGR AMMING L ANGUAGES US $24.99 Twitter: @oreillymedia facebook.com/oreilly St Laurent & Eisenberg 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) Elixir GETTING STARTED IN FUNCTIONAL PROGRAMMING CAN $26.99 ISBN: 978-1-449-36999-6 Simon St Laurent & J David Eisenberg www.it-ebooks.info Introducing Elixir Introducing Elixir 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 ■■ Define macros with Elixir’s metaprogramming tools Introducing 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) PROGR AMMING L ANGUAGES US $24.99 Twitter: @oreillymedia facebook.com/oreilly St Laurent & Eisenberg 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) Elixir GETTING STARTED IN FUNCTIONAL PROGRAMMING 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 corporate@oreilly.com Editors: Simon St Laurent and Meghan Blanchette Production Editor: Melanie Yarbrough Proofreader: Amanda Kersey Indexer: J David Eisenberg September 2014: Cover Designer: Karen Montgomery Interior Designer: David Futato Illustrator: Rebecca Demarest 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 Getting Comfortable Installation Installing Erlang Installing Elixir Firing It Up First Steps Moving Through Text and History Moving Through Files Doing Something Calling Functions Numbers in Elixir Working with Variables in the Shell 1 2 3 Functions and Modules 11 Fun with fn And the & Defining Modules From Module to Free-Floating Function Splitting Code Across Modules Combining Functions with the Pipe Operator Importing Functions Default Values for Arguments Documenting Code Documenting Functions Documenting Modules 11 13 13 16 17 18 19 20 21 22 23 iii www.it-ebooks.info Atoms, Tuples, and Pattern Matching 25 Atoms Pattern Matching with Atoms Atomic Booleans Guards Underscoring That You Don’t Care Adding Structure: Tuples Pattern Matching with Tuples Processing Tuples 25 25 27 28 31 33 33 34 Logic and Recursion 37 Logic Inside of Functions Evaluating Cases Adjusting to Conditions If, or else Variable Assignment in case and if Constructs The Gentlest Side Effect: IO.puts Simple Recursion Counting Down Counting Up Recursing with Return Values 37 37 40 41 42 43 44 45 46 47 Communicating with Humans 51 Strings Multiline Strings Unicode Character Lists String Sigils Asking Users for Information Gathering Characters Reading Lines of Text 51 53 54 54 55 56 56 58 Lists 61 List Basics Splitting Lists into Heads and Tails Processing List Content Creating Lists with Heads and Tails Mixing Lists and Tuples Building a List of Lists 61 63 64 66 68 68 Name-Value Pairs 73 Keyword Lists iv | 73 Table of Contents www.it-ebooks.info Lists of Tuples with Multiple Keys Hash Dictionaries From Lists to Maps Creating Maps Updating Maps Reading Maps From Maps to Structs Setting Up Structs Creating and Reading Structs Pattern Matching Against Structs Using Structs in Functions Adding Behavior to Structs Adding to Existing Protocols 75 76 77 77 78 78 78 79 79 80 80 82 84 Higher-Order Functions and List Comprehensions 87 Simple Higher-Order Functions Creating New Lists with Higher-Order Functions Reporting on a List Running List Values Through a Function Filtering List Values Beyond List Comprehensions Testing Lists Splitting Lists Folding Lists 87 89 90 90 91 92 92 93 94 Playing with Processes 97 The Shell Is a Process Spawning Processes from Modules Lightweight Processes Registering a Process When Processes Break Processes Talking Amongst Themselves Watching Your Processes Watching Messages Among Processes Breaking Things and Linking Processes 97 99 102 102 104 105 107 109 110 10 Exceptions, Errors, and Debugging 119 Flavors of Errors Rescuing Code from Runtime Errors as They Happen Logging Progress and Failure Tracing Messages Watching Function Calls 119 120 122 123 125 Table of Contents www.it-ebooks.info | v Writing Unit Tests 126 11 Storing Structured Data 131 Records: Structured Data Before structs Setting Up Records Creating and Reading Records Using Records in Functions Storing Data in Erlang Term Storage Creating and Populating a Table Simple Queries Overwriting Values ETS Tables and Processes Next Steps Storing Records in Mnesia Starting up Mnesia Creating Tables Reading Data 131 132 133 134 136 138 142 143 144 146 146 146 147 151 12 Getting Started with OTP 153 Creating Services with gen_server A Simple Supervisor Packaging an Application with Mix 154 159 162 13 Using Macros to Extend Elixir 167 Functions versus Macros A Simple Macro Creating New Logic Creating Functions Programatically When (Not) to Use Macros Sharing the Gospel of Elixir 167 168 170 171 173 173 A An Elixir Parts Catalog 175 B Generating Documentation with ExDoc 183 Index 187 vi | Table of Contents www.it-ebooks.info Preface Elixir offers developers the functional power and concurrent resilience of Erlang, with friendlier syntax, libraries, and metaprogramming Elixir compiles to Erlang byte code, and you can mix and match it with Erlang and Erlang tools Despite a shared foundation, however, Elixir feels very different, perhaps more similar to Ruby than to Erlang’s an‐ cestor Prolog Introducing Elixir will give you a gentle guide to this powerful language This release of Introducing Elixir covers version 1.0.0 We will up‐ date it as the language evolves If you find mistakes or things that have broken, please let us know through the errata system Who This Book Is For This book is mostly for people who’ve been programming in other languages but want to look around Maybe you’re being very practical, and a distributed model, with its resulting scale and resilience advantages, appeals to you Maybe you want to see what this “functional programming” stuff is all about Or maybe you’re just going for a hike, taking your mind to a new place I suspect that functional programming is more approachable as a first language, before you’ve learned to program in other paradigms However, getting started in Elixir— sometimes even just installing it—requires a fair amount of computing skill If you’re a complete newcomer to programming, welcome, but there will be a few challenges along the way Who This Book Is Not For This book is not for people in a hurry to get things done vii www.it-ebooks.info If you already know Elixir, you don’t likely need this book unless you’re looking for a slow brush-up If you already know Erlang, this book will give you an opportunity to see how things are different, but odds are good that you understand the key structures If you’re already familiar with functional languages, you may find the pacing of this gentle introduction hopelessly slow Definitely feel welcome to jump to another book or online documentation that moves faster if you get bored What This Book Will Do For You You’ll learn to write simple Elixir programs You’ll understand why Elixir makes it easier to build resilient programs that can scale up and down with ease You’ll be able to read other Elixir resources that assume a fair amount of experience and make sense of them In more theoretical terms, you’ll get to know functional programming You’ll learn how to design programs around message passing and recursion, creating process-oriented programs focused more on data flow Most importantly, the gates to concurrent application development will be open Though this introduction only gets you started using the incredible powers of OTP, that foundation can take you amazing places Once you’ve mastered the syntax and learned about Elixir’s expectations for structuring programs, your next steps should be creating reliable and scalable applications - with much less effort than you would have needed in other approaches! How This Book Works This book tries to tell a story with Elixir You’ll probably get the most out of it if you read it in order at least the first time, though you’re always welcome to come back to find whatever bits and pieces you need You’ll start by getting Elixir installed and running, and looking around its shell, IEx You’ll spend a lot of time in that shell, so get cozy Next, you’ll start loading code into the shell to make it easier to write programs, and you’ll learn how to call that code and mix it up You’ll take a close look at numbers because they’re an easy place to get familiar with Elixir’s basic structures Then you’ll learn about atoms, pattern matching, and guards —the likely foundations of your program structure After that you’ll learn about strings, lists, and the recursion at the heart of much Elixir processing Once you’ve gone a few thousand recursions down and back, it’ll be time to look at processes, a key part of Elixir that relies on the message-passing model to support concurrency and resilience viii | Preface www.it-ebooks.info ... Installation Installing Erlang Installing Elixir Firing It Up First Steps Moving Through Text and History Moving Through Files Doing Something Calling Functions Numbers in Elixir Working with... 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. .. Simon has written or co-written books, including Introducing Erlang, Learning Rails 3, and XML Pocket Reference, Third Edition (all O’Reilly) Elixir GETTING STARTED IN FUNCTIONAL PROGRAMMING CAN