Now that we finally have our React app mostly set up, we can start building out our Phoenix backend. But before we jump into Phoenix, we should go into some of the basics of functional programming and Elixir. This is a long and dense chapter, so you might want to come back to it after a few lessons when you've had a chance to play around with Phoenix.
Elixir is a functional programming language. We could write an entire course simply going over the features of the language, but in this lesson we will just go over some of the specifics of the syntax that you will need to know before moving forward.
Most of what is covered in this lesson are the specifics of Elixir as they relate to Phoenix. The intricacies of Phoenix will be covered in later lessons as they come up.
Before we dive into Elixir and Phoenix, we'll explore the fundamentals of functional programming.
There are two camps in computer programming: Functional programming (often abbreviated FP) and Object Oriented Programming (often abbreviated OOP). There is overlap between these camps, but they differ in their approach to programming.
Most people have experience with OOP, which intentionally mimics objects representing real life things and interactions. Another big part of object oriented programming is state. State refers to information stored in an application, object, or variables. Many popular programming languages are object oriented such as Java, JavaScript, C++, and Ruby to name a few.
For example, one can imagine a real-life object, such as a block of clay. You can then mutate that block of clay, apply heat, and end up with a vase.
vase = Clay.newvase.shapevase.heatvase.glazeIn the above example the vase contains information about itself and whether it has been shaped, heated, or glazed; this is state. Another example of state, using JavaScript, is the += or -= operators which modify an existing variable rather than return a new one:
var counter = 0counter += 5counter -= 1counter += 2console.log(counter) // -> 6Functional programming is a bit more abstract, and functional programming advocates are more hardcore about definitions than object oriented folks. You'll hear a lot about "immutable data" and "pure functions", and a variety of other terms. We will go over the terms that are relevant to working with Phoenix and Elixir.
One of the core concepts of functional programming is the "pure function". A pure function is a function that always yields the same results with the same arguments and has no side effects. You may also hear them referred to as "idempotent" (pronounced īdemˈpōt(ə)nt), which is a fancy way of saying "it has no side effects".
A side effect is something like writing to a database, or making a change to something that is outside the scope of a function. They are changes that, if run again, may produce a different outcome. Additionally, pure functions need everything passed to them as arguments; retrieving values elsewhere could lead to a different outcome.
Here is an example of an impure function:
var counter = 0function addOne() { counter += 1}addOne()Our example has a state, counter, outside the scope of the function that is modified by our function. If you run it once, the result is 1. If you run the exact same function twice, the result is 2.
This side effect wouldn't be possible with a pure function. An example of a pure function would be the following:
function addOne(counter) { return counter + 1}var counterPlusOne = addOne(2)In this example, we are passing the counter in as an argument to the function, which then adds one and returns the new result. No matter how many times you run this function, it will always give you the same result (3).
Pure functions are important to functional programming because they allow us to chain together functions, perform multiple transformations to data, and get a predictable result without side-effects. This lack of side-effects is the foundation of Elixir's fault tolerance and ability to re-try code without fear; this is something we'll discuss more later. As we will see shortly, Plugs are an important part of Phoenix and are themselves, by necessity, pure functions.
In functional programming we do not mutate data, instead we create a new copy with our changes. This may seem like a lot of extra work at first but functional programming languages are designed for this. This immutable data furthers our ability to ensure predictable outcomes and allows for the more advanced features of Elixir's concurrency and fault tolerance. Don't worry though, we'll cover all of this in more depth in later lessons.
If you are interested in learning more about functional programming, there is an edX course that covers a lot more than we will cover in this course.
Elixir ships with IEx, an interactive shell. With IEx we can evaluate Elixir expressions and test out functionality before adding it to our code base. The best way to understand IEx is to experience it. In your terminal, run the iex command.
$ iexYou'll get an output similar to the one below.
Erlang/OTP 18 [erts-7.1] [source] [64-bit] [smp:8:8] [async-threads:10] [hipe] [kernel-poll:false] [dtrace]Interactive Elixir (1.2.0) -press Ctrl+C to exit (type h ENTER for help)iex>We are now in an interactive environment where we can explore Elixir and evaluate expressions. Let's start with trying to run some simple Elixir code. Inside IEx let's add together some numbers. If we type in 2 + 2 and press return, the expression is evaluated and the result is displayed.
iex> 2 + 24iex> 2.5 + 13.5As you might expect coming from JavaScript, Ruby, or other major languages Elixir has support for the basic types you'd expect. With IEx open, let's try working with some integers and floats.
iex> 1 + 23iex> 2.0 + 2.54.5Elixir supports the booleans true and false, they are also represented by the atoms (explained momentarily) :true and :false. All values in Elixir, with the exception of nil and false, are considered truthy.
iex> truetrueiex> true === :truetrueiex> falsefalseiex> if 6, do: "Truthy""Truthy"If you're familiar with Ruby then atoms won't be foreign to you, they're just like symbols. If you're new to both, don't worry.
In Elixir an atom is a constant who's name is also its value. They are lowercased and begin with a colon. :ok and :error are example atoms. What makes Atoms special is how they use memory. When we use the atom :ok many times the memory is only allocated once. Atoms are great when we need to reuse the same value many times and wish to conserve memory. Unlike other values though, atoms are not garbage collected so they should be used sparring; if we always used atoms in place of other values, our memory would never be freed.
TODO SEAN need to explain what garbage collection is
Strings are UTF-8 encoded and use double quotes, let's try the standard "Hello World":
iex> "Hello World""Hello World"What about single quoted values like 'hello world'? In Elixir, single quotes are used to denote char lists. A char list is nothing more than a list of individual characters:
iex> 'hello world''hello world'iex> is_list('hello world')trueChar lists can be tricky in IEx. If characters are outside the ASCII range then a list of character codes will be displayed instead; these character codes are the numerical value for each character:
iex> 'hełło'[104, 101, 322, 322, 111]Collections are a big part of functional programming. As we'll see, Elixir has a number of different data structures available to us. The simplest of these collection is the list. Lists may contain different types of values and do not enforce uniqueness, we can store the same value in a list many times.
Let's try creating some simple lists inside IEx:
iex> [1, 2, 2, 3, 3, 3][1, 2, 2, 3, 3, 3]iex> [1, 2, 3, "a", "b", "c"][1, 2, 3, "a", "b", "c"]If you don't have a background in FP then tuples may seem strange to you but tuples are a common sight in Elixir. A tuple is similar to a list but is stored in memory contiguously, making accessing them fast but modification expensive. Tuples are differentiated from lists by using curly braces. Just like list our tuples can contain any type of value and do not enforce uniqueness:
iex> {:ok, "Success"}{:ok, "Success"}iex> {10, "ten", :ten}{10, "ten", :ten}You can think of tuples as something like a pair of values that are meant to be stored together. They aren't there for efficient modification.
If we combine lists, tuples, and atoms together we get keyword lists in Elixir. A keyword list is a collection of two-element tuples who's first value is an atom, very specific. Keyword lists are frequently used for options and configuration. A keyword list can contain multiple tuples with the same key.
iex> [age: 30, name: "user"][age: 30, name: "user"]iex> [{:age, 30}, {:name, "user"}][age: 30, name: "user"]Maps are the go-to key-value store in Elixir. We can use any value as a key in our maps. To define a map we use the %{} syntax:
iex> map = %{"hello" => :world, :ok => 200}%{:ok => "okay", "hello" => "world"}iex> map[:ok]200iex> map["hello"]:worldKeys in a map are unique, if we add a new value with the same key it will replace the original.
iex> %{"hello" => "world", "hello" => "universe"}%{"hello" => "universe"}If you haven't used functional programming before then pattern matching may seem a bit strange at first, but it is arguably one of the best features of Elixir. When we use pattern matching we not only compare values but structure as well.
Through pattern matching we are also able to extract values from a match into a variable, this is known as variable capture. In a moment we'll try some examples which should help clear things up, but first we need to discuss the match operator.
Unlike other languages Elixir does not use the = operator for value assignment, instead it is use as our match operator.
Confused yet? When we make a successful match, the matched value will be returned. If the match fails, it will raise an error. In IEx, let's start with a few simple pattern matches to get our feet wet.
iex(24)> "hello" = "hello""hello"iex> [1, 2] = [1, 2][1, 2]iex> [1, 2] = {1, 2}** (MatchError) no match of right hand side value: {1, 2}In our next example we'll introduce variable capture. In it's simplest form variable capture does resemble an assignment (like the "=" in JavaScript) but it's important to remember they're different. To better visualize the difference, and to demonstrate the power of variable capture, let's try some examples.
Start with the simple a = 1 match. In this instance the value of 1 is captured in the variable a. Although it may look like an assignment, it's important to remember it is not. To better illustrate the difference, and power of variable captures, let's try matching [1, b] to [1, 2]. Our match will be successful and if we look at the variable b, we should get 2.
iex> a = 22iex> a2iex> [1, b] = [1, 2][1, 2]iex> b2Be aware that variable capture works right to left. Variables included on the right side of the match are evaluated and their values used. With our previous example as a starting point, use [a, b] on the right side of a match to demonstrate how the values are used.
iex> [1, 2] = [a, b]** (CompileError) iex:1: undefined function a/0What if we need to use a variable's value in a match but don't want to reassign the value of that variable? To accomplish this, we can use variable pinning, available to us through the pin operator: ^. Let's try some examples with the pin operator.
To begin let's capture a value into a variable, something like a = 1 will work. Next we'll use our variable and pin operator, ^a, as part of a match. To demonstrate a successful match, let's try to match [^a, 2] to [1, 2]. If we change the right side to [2, 2] we should get a match error.
iex> a = 11iex> [^a, 2] = [1, 2][1, 2]iex> [^a, 2] = [2, 2]** (MatchError) no match of right hand side value: [2, 2]You may not find yourself using variable pinning much but it's an important piece to be aware of.
We're going to go into functions and modules in the next lesson as well as some of the basics of Phoenix and the Model-View-Controller.
Previous: Unit Tests with EnzymeNext: More Basics of Elixir and Phoenix