Elixir supports if and unless like other modern languages such as Ruby and CoffeeScript. If you aren't familiar with unless, don't worry it's just syntactic sugar for: if !value.
iex> if true do...> "truth"...> else...> "false"...> end"truth"If we replace if with unless, we should get the opposite.
iex> unless true do...> "true"...> else...> "false"...> end"false"Elixir doesn't stop with just if and unless, it includes two addition control structures: case and cond. The case structure is similar to a switch statement in other languages but it relies heavily on pattern matching. The best way to understand the case statement is to try it in IEx.
iex> case {:ok, "Success"} do...> {:ok, value} -> value...> _ -> "No match"...> end"Success"You may have noticed an underscore (_) above. An underscore is a placeholder that accepts any value. So in the example above, if the case does not match {:ok, value}, then it will pass to _ which will match with anything else and return "No match".
Last but not least is cond. We can use cond when we want to match conditions and not values or patterns. The cond structure is similar to else if in other languages. An example will help us better understand it's usage.
iex> val = 44iex> cond do...> val + 2 < 4 -> "val < 2"...> val + 2 >= 4 -> "val >= 2"...> end"val >= 2"One of the nicest syntactic features of Elixir is the pipe operator, |>, which allows you to "pipe" a value from one function to another function. This is very similar to the unix pipeline | if you've ever used that. In its simplest form, the |> takes the left value and passes it to the right side as the first argument.
This is particularly useful because Elixir is just collections of functions, piping them together makes the code expressive and easy to understand at a glance. For example, if were were to make a cake using functions, we could write.
ingredients|> measure|> mix|> bake|> decorateEach step takes the result of the previous function and applies a transformation to it. This is a surprisingly powerful abstraction that makes it very easy to understand the flow of your app and makes for highly-maintainable code.
Functions in Elixir, and other functional programming languages, are considered first class citizens. That means that all operations available to other types are available to them, they can be passed as arguments to other functions, assigned to variables, and returned from other functions.
In Elixir there are a couple types of functions, but for this section we'll focus on anonymous functions. As the name suggests, anonymous functions have no name. If not captured in a variable, an anonymous function would otherwise not exist. To define an anonymous function we'll use the fn (arg) -> body end syntax. To call an anonymous function we use the .() syntax on our variable, which is similar to what you find in other languages.
Let's start with an example function to add two numbers together and then try using it.
iex> add = fn (a, b) -> a + b end#Function<12.54118792/2 in :erl_eval.expr/5>iex> add.(1, 2)3Elixir also includes a helpful shorthand syntax for anonymous functions. This shorthand makes use of the & operator. With the shorthand syntax our arguments are referred to as &1, &2, and so on. We can try our previous example using the shorthand syntax.
iex> add = &(&1 + &2)&:erlang.+/2iex> add.(1, 2)3We learned about pattern matching using the match operator (=) but we can also use it when specifying function signatures. Let's expand on our prior example. Let's update the function to return the string "zero" if someone tries to add 0 and 0 together:
iex> add = fn...> (0, 0) -> "zero"...> (a, b) -> a + b...> end#Function<12.54118792/2 in :erl_eval.expr/5>iex> add.(1, 2)2iex> add.(0, 0)"zero"That's just the start of functions in Elixir. In the next section, and later lessons, we'll cover other function types and how they all fit together.
At their most basic, modules are collections of functions. With defmodule we can create a new module, add functions to it, and then re-use it elsewhere in our application. We'll learn more about modules in later lessons, but for now we'll focus on the basics.
We've already covered anonymous functions so let's take a look at functions with regards to modules. In our anonymous functions we used the fn -> ... end syntax, but named functions (or functions in modules) use def and a lowercase name.
Let's create a simple example module that can add two numbers together. We can start by using defmodule Example to define our module. Then we'll need to use def add(a, b) to define our function, implementing the functionality should be easy. Once we've defined everything we can use it by calling Example.add(1, 2). If we put it all together we should get something like this:
iex> defmodule Example do...> def add(a, b) do...> a + b...> end...> end{:module, Example, <<70, 79, 82, 49, 0, 0, 4, 248, 66, 69, 65, 77, 69, 120, 68, 99, 0, 0, 0, 157, 131, 104, 2, 100, 0, 14, 101, 108, 105, 120, 105, 114, 95, 100, 111, 99, 115, 95, 118, 49, 108, 0, 0, 0, 4, 104, 2, ...>>, {:add, 2}}iex> Example.add(1, 2)3You might be confused by all the numbers that Elixir has outputted for us. For now, don't worry about it because we won't be using that information any time soon. But if you insist on jumping ahead, you can check out Elixir binaries.
That's the tip of the iceberg for modules. In the next lessons we'll learn more about composing our modules and connecting the pieces.
When we need a named key-value store with known keys, we turn to structs. Structs share the name of the module they're defined in and use a syntax similar to our maps. We define them with defstruct and a keyword list of fields and default values. For our example, let's create a simple module and struct to present a person:
iex> defmodule Person do...> defstruct name: nil, age: 0, location: nil...> end{:module, Person, <<70, 79, 82, 49, 0, 0, 5, 32, 66, 69, 65, 77, 69, 120, 68, 99, 0, 0, 0, 133, 131, 104, 2, 100, 0, 14, 101, 108, 105, 120, 105, 114, 95, 100, 111, 99, 115, 95, 118, 49, 108, 0, 0, 0, 4, 104, 2, ...>>, %Person{age: 0, location: nil, name: nil}}Now that we have our struct created, it's time to use it. As we already learned, structs and maps share a similar syntax. In fact, structs are just maps with a few extra features. Create a new struct containing your information and try to access the fields:
iex> sean = %Person{name: "Sean", age: 31, location: "US"}%Person{age: 31, location: "US", name: "Sean"}iex> sean.age31It's no coincidence that Elixir and Ruby share many similarities; Jose, the creator of Elixir, was a contributor to Ruby and Rails.
Phoenix is the framework we'll be using with Elixir. If you've used an MVC framework such as Rails or SailsJS, a lot these topics will be familiar to you.
Phoenix uses the standard Model-View-Controller (MVC) architecture that we have come to expect while building web apps. In general, anything related to the web application can be found in the web directory. In there we will find out models, views, templates, and controllers. For those unfamiliar with MVC, we'll do high level overview.
The appeal of the MVC pattern is the separation of concerns. As you probably guessed there are three components to the MVC pattern: models, views, and controllers. Another way of saying that is: data, user interface, decisions. In a MVC application the model is responsible for managing data and business rules. Our view handles the user interface be it HTML, XML, or JSON. Finally, our controller handles most of the work orchestrating inputs to models and finally views.
Most of the logic of how the user interacts with the app will be handled by the controller. You will see this in practice in short order, so there is no reason to go into detail here.
We will cover Phoenix and Elixir in more detail as the concepts become relevant in the rest of the tutorial.
In Phoenix, most files are named with _ underscores. For example, user_controller.ex.
When debugging, most people use IO.puts to log some particular output to the terminal. For example, IO.puts "Running!" will simply return a string if it is called.