Book Image

Elixir Cookbook

By : Paulo Pereira
Book Image

Elixir Cookbook

By: Paulo Pereira

Overview of this book

Table of Contents (16 chapters)
Elixir Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Using the terminal to prototype and test ideas


The Elixir default installation provides an REPL (short for read-eval-print-loop) named IEx. IEx is a programming environment that takes user expressions, evaluates them, and returns the result to the user. This allows the user to test code and even create entire modules, without having to compile a source file.

To start prototyping or testing some ideas, all we need to do is use IEx via our command line.

Getting ready

To get started, we need to have Elixir installed. Instructions on how to install Elixir can be found at http://elixir-lang.org/install.html. This page covers installation on OSX, Unix and Unix-like systems, and Windows. It also gives some instructions on how to install Erlang, which is the only prerequisite to run Elixir.

How to do it…

To prototype and test the ideas using IEx, follow these steps:

  1. Start IEx by typing iex in your command line.

  2. Type some expressions and have them evaluated:

    iex(1)> a = 2 + 2
    4
    iex(2)> b = a * a
    16
    iex(3)> a + b
    20
    iex(4)>
    
  3. Define an anonymous function to add two numbers:

    iex(5)> sum = fn(a, b) -> a + b end
    Function<12.90072148/2 in :erl_eval.expr/5>
    
  4. Invoke the function to add two numbers:

    iex(6)> sum.(1,2)
    3
    
  5. Quit from IEx by pressing Ctrl + C twice.

How it works…

IEx evaluates expressions as they are typed, allowing us to get instant feedback. This allows and encourages experimenting ideas without the overhead of editing a source file and compiling it in order to see any changes made.

Note

In this recipe, we used the = operator. Unlike other languages, = is not an assignment operator but a pattern matching operator. We will get into more detail on pattern matching in the Using pattern matching and Pattern matching an HTTPoison response recipes in Chapter 2, Data Types and Structures.

In step 3, we used a dot (.) in the sum function right before the arguments, like this: sum.(1,2). The dot is used to call the anonymous function.

There's more…

It is possible to define modules inside an IEx session.