Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman, PhD

Hi and welcome to the course. Thanks for joining. Let’s dive right in.

The first thing we have to do is obviously install Elixir. For that we’re going to head over to http://elixir-lang.org.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

In this video, we’re going to discuss installation on Windows and in the next few videos we’re going to take a look at how to do that in Linux and on Mac. When you head over to http://elixir-lang.org you will see the install tab over here, you can click on that and you will arrive at this page which allows you to view instructions for installing Elixir on different distributions.

You have a Mac, UNIX, Windows, Raspberry Pi, Docker, and a lot of options. Here we are going to take a look at the windows option. That’s fairly simple. You click on Windows and you arrive at this installer link. Click on the installer link and you will have the Elixir – web setup.exe file download. Once you have that, simply open this file and it’s going to start as a setup wizard for you.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

Simply click on yes or next or whatever the default options are and you should be good. When we click on Next, the latest version is 1.7.3 at the moment. You can install whatever the latest version is when you’re viewing this, so when we click on next the defaults work fine for everything. You click on install.

Now, it might ask you to install the .net redistributable if it does you can simply go ahead and accept that license as well, and it’s going to install the. net redistributable for you. I’m going to skip ahead in time until this is all done and then we come back to it.

Once the download is done you can go ahead and click on Next to keep it with the defaults, and everything should be installed perfectly well for you.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

You get the Microsoft Visual C++ redistributable message, so you agree to the license, and click on install. It is going to be installed as well. Click on close and just wait for it to finish copying everything that’s needed. This is done. Let’s go ahead and click close and it’s going to go ahead and do some extraction for the actual Elixir after the Erlang OTP is done.

All of this is perfectly automated, you don’t have to do anything, you just have to wait for it to finish doing its thing.

Once everything is done we click on finish and if we have a command prompt open start a new one. We are going to type iex. This is the interactive shell for Elixir, hit enter, and we’re there.

Now we’re going to say IO.puts that is the print equivalent of Elixir, and we’re going to say “Hello World!” That’s our hello world. It’s working and now we can hit Ctrl+ C to exit and hit Y to confirm.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

Elixir is setup and in the next part we’re going to do something really interesting with it.

Before we jump into explaining what Elixir is and how it works, I’m going to show you a very quick case study demonstrating why Elixir is so awesome.

What we’re going to do is we’re going to start up with command prompts. I’m on the Mac but you can do the same thing on Linux or Windows, so just start up two terminals or command prompts on Windows. In one type iex– name alice.

This terminal, this specific instance of iex is going to be called Alice, so let’s start that, and in the other terminal let’s start another instance by the name of Bob iex– name bob, and so we have that. Both of these are running let’s go ahead and clear this.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

What we’re going to do is we’re going to create a simple function in this alice instance, and then we’re going to call it from the bob instance, so this is going to be an inter process communication done really quickly and really easily.

Since Elixir is a functional programming language everything should live in a function, and functions are connected together in what are called modules. What we’re going to do is we’re going to define a simple module over here using defmodule. You don’t have to understand what the syntax is at the moment. We’re going to get into the details of that later on.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

We are just trying to demonstrate this really cool feature. So defmodule hello do, and in this module we’re going to have a function world and that function is simply going to say IO.puts “Hello World”. That’s all it does so end the function, and end the module.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

If you get some stuff out you don’t have to worry about that. Hit clear and now we can say Hello.world () and that is going to output Hello world, so nothing interesting at the moment.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

Let’s go to our bob instance and from here try to say Hello.world(). Obviously this does not work. The function is undefined. What’s really cool is that we can communicate between these two instances that can be in separate processes or they can even be on separate machines. How do we do that? We say Node.spawn(:”alice@zebox.local”, fn Hello.world() end. This end matches with this function. Just a little bit of syntax but with that you can go ahead and execute a function in a completely different process.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

If you will enjoy reading and contributing to the discussion for this post, will you please join us on the YouTube video above and leave a comment there because I read and respond to most comments on YouTube?

If you find anything helpful in this video or funny, will you please leave a like because you will feel great helping other people find it?

There you go. The process on Alice’s terminal has executed the function and it has returned the output to the process on Bob’s terminal. This is how easy it is to create distributed applications in Elixir. You get all the RPC – all the inter-process communication essentially for free, so that’s a very interesting idea. It shows you how much Elixir focuses on distributed code and that is one of the reasons why Elixir is so efficient and so highly scalable.

Now, We’re Going To Step Back And Go To The Very Basics Of The Language And Learn It From Scratch.

Once Elixir has been successfully installed, we can go ahead and start the Elixir interactive shell using the command iex It doesn’t matter which operating system you’re on. This is going to work on Windows, Mac, or Linux so as long as you have installed Elixir properly iex should be available, and we can go ahead and execute this.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

As you can see we are in the interactive Elixir shell and we can type Ctrl+C to exit and h function will provide help.

As before, I have made available all the commands that I am going to execute over here in a markdown file so all the Elixir commands that we are going to execute are going to be in the Elixir code block. That starts from over here and goes all the way to the three backticks.

You can also see the same file in a Pdf version and it’s going to show you a slightly neater output if you want to print it out.

Anyway, let’s go back to our interactive shell and execute some Elixir. If you’ve had some experience with Python or any other interactive language you would know that we can simply go ahead and execute the expressions in this shell.

For instance, I can type 3 and hit enter and it will return the value of 3 which is 3 itself. We can also go ahead and say 5 + 9 and that’s going to be executed and we’ll get 13 back. These are expressions and they follow the same syntax that you would be comfortable with. We can say 5/9 we can say 16-9, we can say 5+18. Anything that you really want and you can also have parentheses so (5+4), (5+2)-5 and you get 2 back, so anything that you can really think of that works over here.

You can go ahead and experiment with all the expressions that you’re already comfortable with, we’re going to go ahead and move to something more interesting. Let’s go ahead and assign this value to x=34. We can say x=34 and as you can see the value 34 is returned back and X has been bound to 34.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

There is a little bit of detail as far as Elixir goes on this but we’re going to skip that at the moment and then come back to it later on. X=34 you can think of it as simply X being bound to the value of 34.

We can clear the screen by entering the clear command which I just did and now what we can do is we can go ahead and reassign the value of X to some other value, so we can say x=10.0.

Now you will notice that we are not defining the type of X and that means that Elixir is dynamically typed. It’s going to interpret the type of the variable by looking at the value that it holds, so x is currently a float because it holds the value of 10.0.

We can also have strings so we can say “String here” and that defines a string.

The difference between Elixir and Python is that Elixir has strings in double quotes. A string enclosed in a single quote is something else. We’re not concerned with what that is at the moment but just remember if you’re going to use strings you have to enclose them in double quotes.

We can also have booleans so we have truth, we have false, and we have boolean operators of and and or. Same semantics as before true and false is going to be false true or false is going to be true. Now you can go ahead and practice with all of the different types of expressions you can have multiplications, divisions, boolean operators, you can have strings, and you can go ahead and practice with them so that you get comfortable with it.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

If you’re coming from Python this should come naturally to you and you don’t have to waste time on it. There is one thing though that is extremely important in Elixir and that does not happen in Python, so let’s go ahead and take a look at that. Let’s clear this and the concept is called atoms and an atom is a constant whose name is its own value, so it’s a little difficult to explain but very easy to demonstrate. We can say :foo starting with a colon and that’s going to have the same value :foo. If we say y that’s going to give us an error because y is not defined but if we say :y that works because :y is an atom.

An atom is something that starts with a colon and it’s going to be a constant that is going to be its own value. These come in handy in a lot of the different aspects of Elixir so you just have to be aware of them.

It’s not a complicated concept, it’s just something that you might not have seen before.

An atom is something that holds its own value so an atom is a constant whose name is its own value, so that’s all we need to know at the moment.

That’s done.

Let’s go ahead and clear this up again and then take a look at some of the built-in data structures for Elixir. As you would know, we have lists so [1,2,4] that’s a list and just as in Python you can have different types of lists, you can have different variable lengths, and you can have any data type going into the list. You can have a heterogeneous list as well. This works perfectly fine.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

We also have the concept of tuples the difference is in Python tuples are defined using () something like that (1, 2), but in Elixir we are going to have tuples defined using {1, 2, 3} so this in Elixir is a tuple so that works as a tuple.

Another thing that you have to be aware of and that’s really important in Elixir is the difference between the lists that are in Python versus the lists that are in Elixir.

The important difference is that in Python lists are mutable – they can change, you can add values to them, you can remove values from them, but tuples are immutable. You cannot modify a tuple once it’s made.

In Elixir both lists and tuples are immutable, you cannot change the value of a list once you have created it, so what good is that? You can always go ahead and add new values to a list but that is going to be a new list. That’s not going to be the oldest. The oldest is going to stay there so you can say x = [1, 2, 4 and now you can go ahead and say that we want to concat this list x ++ [5, 6] so that works perfectly fine except x is still going to be the same list.

If you want to assign it, you have to rebind the value of x with this new list x = x ++ [5, 6]. Now x is going to be changed. This seems like a minor difference but it’s a fundamental difference between how Elixir looks at things in general, so that is the concept of function programming.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

Everything is going to be immutable. You cannot change lists, you cannot change tuples and you cannot change any of the other data structures that we’re going to see later on.

Anything that changes you have to explicitly assign it back to the original variable. Please go ahead and practice with this stuff and in the next part we’re going to go ahead and look at some of the other data structures that are available in Elixir.

Maps in Elixir.

Here we are going to take a look at the third very important essential data structure which is called dictionaries in Python and here they’re called maps. In Python, a dictionary looks like that {“a” : 3, “b” : 4} so a key value pair in which different pairs are separated using commas and the keys and values are separated using colons.

We’re going to change this into the syntax that Elixir understands, so the first thing that we have to do is append a %{“a” : 3, “b” : 4} at the beginning that turns it into a dictionary and the terminology that we use over here is a map. Because the braces are used for tuples we have to prepare a percentage sign to tell Elixir that we’re talking about a dictionary and not a tuple. Then we go ahead and change this colon to this arrow symbol %{“a” => 3, “b” => 4}. Now, we have a dictionary or a map.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

So we’re going to call this a map from now on. Let’s go ahead and assign this to the variable x= %{“a” -> 3, “b” -> 4} and if you now say x we can get %{“a” -> 3, “b” -> 4} over here.

Another syntax that is very handy is that instead of using these strings over here instead of using a string, we can go ahead and use an atom.

We can say instead of this we can go ahead and say :> x = %{:a -> 3, :b ->4}. Same idea except now the keys are atoms and as you can see because the atom is its own value it goes over here as %{a:3, b:4}.

You can use this modified syntax to get rid of this double arrow and simply say > x = %{a: 3, b: 4}. There you go. Essentially the same as Python except instead of having a string colon, we now have an atom colon. it’s slightly more easy to read.

In order to get values out of the map, we can use Map.get(x, :a). So Map.get(x, :a) and the key gives us 3 back over here.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

We can also use the syntax of x[:a] just as we do in Python. So x[:a] gives back 3 and x[:b] gives back 4, but we have another very useful syntax, and we can say x.a.

If we are using atoms over here as keys we can simply say x.a which is not possible if we are using strings as keys. It’s much more common to find Atom being used as keys in maps in Elixir.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

That’s the major difference between dictionaries and maps of Python and Elixir. Once you get the hang of it this is a lot easier to read and work with. As before, I urge you to practice a little bit with this syntax so that you get comfortable with this. Dictionaries and tuples are used repeatedly in Elixir for a lot of things just as they are in Python, so you have to be comfortable with them going forward.

In the next part, we’re going to go ahead and take a look at some of the arithmetic expressions and some of the other operators that we can perform on the basic data types.

Arithmetic Expressions and Operators for Basic Data Types.

We took a look at some expressions so > 1 + 2, > 5 * 5, they all work just as normal. So 9/2 is the proper Python 3 style division. If you want to do integer division you can say div(9,2) and return the integer part of the division. If you want to get the remainder you can say rem(9,2) and that returns the remainder.

An important thing to notice over here is that you cannot have a space between the function name and the bracket, that’s going to be an error > rem (9,2) so you cannot do that, however you can get rid of the brackets altogether by saying rem 9,2 so both of these syntax are equivalent, and both of these are used in Elixir community, so you have to be comfortable with both of them.

We also took a look at boolean so true and you can have the equality operator checking whether true and true are the same. They are, so we get true back. We can check for 3== 3. 3 == 5 returns false. 3 == 3.0 also returns true because double equal to is the equality operator which matches the values. If the values are the same you get true.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

If you want to check whether the value and the datatype are both the same you have to use 3 === 3.0 and this is going to return false because even though the values are the same the data types are different.

If you want to check the datatype of a particular value, you can say is_integer(3). That returns it true. is_integer(3.0) is not an integer, that’s a float. We can check if boolean is_boolean(4) and this returns a false. is_boolean(true) that returns a true.

Let’s say x = 4 and we can say is_boolean(x) and that returns a false. is_integer(x) and that returns a true.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

Those are some basic operations and now what we can do is we can study some strings. If you recall we had “hello” that’s a string.

We can go ahead and check whether “hello” == hello. Recall that double equal only checks the values so even if their data types are different the values sure look the same, but if you hit enter you will see that it’s false. Hello with a double quote and Hello with a single quote are two completely different animals. You cannot compare them together.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

You should get into the habit of using double quotes whenever you’re working with Elixir because a single quote is something completely different.

We can also go ahead and say “hello#(x)” going to be a “hello 4” X is at 4. We can also say “hello#(x+1)”is going to be evaluated to 5 and get “hello 5” out of it. This is called string interpolation and is used very often in Elixir.

It’s a lot more powerful than the concept of string formatting in any other language, and is used very extensively.

We also have multi-line strings so you can simply say “hello enter world” and you get multi-line string without having to use triple double quotes. In Python you wouldn’t have to do triple quotes in order to have a multi-line string, but over here you can simply use it just as you naturally would.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

If you want to use the print statement you can say IO.puts(“hello”) and you get the print out and the :ok is the return value of the puts function. This is the side effect and this is the value of the puts function.

You can also go ahead and say IO.inspect (“hello”) and you get the same string output as the side effect, and then IO.inspect also returns this value back to you. This is the output of the function and this is the value that is returned by the function, so we’ll come back to this later on as well.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

You can also go ahead and get rid of the brackets IO.inspect “hello” same idea. You can also do some string operations so String.upcase(“hello”) is going to convert the hello into an uppercase.

If you want to see what other stuff is available related to strings you can simply go ahead and issue the h command which is the help and here you can put h(string) and you will get a detailed output of the string operations.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

So you have String.split\2. You have String.chunk, you have string.length/1, and you have a lot of the other documentation that is over here with a lot of examples. You can go through them after you’re done with this course and you’re looking for some quick reference, so you can get this over here just as you can get Python’s help using doc or help.

We’re not going to belabor at this point over here, we’ll go back to the functions when we need them. At the moment let’s go ahead and clear this up and take a look at adding some other operations.

We have a [1, 2, 3] list and we can go ahead and concat [4, 5, 6] with it using the concatenation operator for lists which are ++ signs. That’s string concatenation.

We can also have string subtractions so [1, 2, 4] — [4] we get rid of 4 of this and we get [1, 2] back. We can also get rid of the [1, 2, 4] — [2, 4] and just get the 1 back.

Another operation over here which is really, really useful is let’s go ahead and save this lst = [1,2,4,6 ]. That’s our list and now what we want to do is we want to get the first element out of it. If you’re comfortable with recursion you would know that it’s very important to get the first element out because you want to do some operation on the first element, and then you want to do the operation on the rest of the elements. The way to do that is to use the hd function so you say hd(lst) and you get the first element back. You can also say tl(lst) and that’s going to return the tail or the rest of the list.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

Now you can split the list between its head and everything else.

Let’s say you want to sum up all of the elements in a list that you can do is add the value of the head with the sum of the rest of the list.

sum(list) = value of head + sum(rest of the list).

This is very handy and we’re going to come back to this in future lectures as well. Here you just need to remember that head returns the first element as an element not as a list, and tail returns the rest of the list as a list.

So you can always go ahead and put these into let’s say is a = hd(lst) and if you say b = tl(lst) is equal to and if we say b that’s this guy, so now we have a and b and we can go ahead and process them separately.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

If you want to inspect different values we can say i and then put the value out so i 35 tells you that the term is 35. the data type is integer and some other stuff as well that we are not concerned with at the moment.

We can also say x = 45 and then say i x and it’s going to return the value. The term is 45, data type is integer, and so on and so forth.

We also took a look at tuples so let’s say we have a tuple over here so t = {:ok, “hello”}. You can have different types. This is perfectly fine in fact it’s used a lot in Elixir so we’re taking a look at it right now. T is this tuple it’s not a map its tuple with two elements and we can say the elem(t, 1) should be returned and as you can see this a zero-based indexing, so this is zero element and this is the element number 1. You can say elem(t, 0) and that gives you back the first element over here.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

One final thing we want to do in this video is to take a look at the error, so let’s go ahead and clear this.

If you’ve even had a little bit of programming experience you would know that understanding errors is extremely important, so what we’re going to do over here is try to call a function which is missing. Nobody defines this function and we’re trying to call it and the error that we get out over here needs to be understood. Let’s go ahead and read this. So this is a compiler error which means that there was some compile time problem and missing functions are compile time errors in Elixir.

Because in Elixir everything that you write is going to be compiled and then it’s going to be executed. That means that the Elixir executables are extremely fast. Unlike Python, Elixir is extremely fast. It gives you all the benefits of Python but it also has the extreme benefit of being very, very fast.

In fact we discussed in the introductory videos that Elixir is one of the fastest languages that you can work with, and it’s highly scalable because of this concept of compiling stuff first before executing it.

We have the compile error over here it tells you where the error is so iex:126 because this is the 126 line that we are executing. Then you have the error description which is an undefined function and this last part is the most important part so missing_function /1. What this means is that the name of the function that’s missing that we cannot find which is undefined is missing underscore function a function that takes only one argument, so this 1 defines the number of arguments.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

Instead of missing _function (3, 4) it would say missing function /2 because now it’s trying to find a function missing function which has two parameters. Even if there was a function defined which had one parameter it would not be able to find it.

A function which takes one argument is a completely different thing in Elixir from a function which takes two arguments. In typical programming languages we define a function using just a name. In Elixir we define a function using a function name and what is called an arity – the number of parameters.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

That’s a function_name/arity pair. That is what defines a function in Elixir. That’s all we wanted to do right now and in the next part we’re going to take a look at some of the other concepts of Elixir which are essential for the understanding of the language.

What Are Parallels in Elixir?

In this section we’re going to take a look at a concept that is unique to Elixir. A parallel is not available in Python so it’s slightly difficult to get your head around it if you have not worked with Elixrs before.

Let’s start with a very basic example so we have started our Elixir interactive shell and we type x = 25 so that looks like an assignment operator it works fine. What this does is it takes the variable X and binds it to the variable 25, so this is what we call assignment. What we can also do is say 25 = x. What that means is it’s going to try and match this whole expression and in order to do that x must have a value of 25 and because x does have a value of 25, we are going to get a 25 back.

This is perfectly valid Elixir and you’re going to see why this is useful. We can also try and do 35 = x and that is going to fail. The reason is that the value of x is 25 and there is no possible combination that we can put in this expression that is going to satisfy this whole expression.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

This is a match error so essentially when we say 25 = x it’s trying to match 25 with x. When we are trying to say x = 25 that is also trying to match x with 25 except for the fact that, on the left side of the equal to operator whenever something occurs you can assign it.

If we say x = 10 it’s going to try and match it. x is not going to match because 25 is equal to 10 does not match but because x is a variable and is to the left of the equal to operator it’s going to be rebound, so x = 10 is perfectly valid.

However sometimes you want to make sure that only a match is done and not a reassignment or rebinding. For that you can use this operator. This is the ^ symbol and you say ^x = 25 and now it’s not going to try and rebind it’s only going to try and match, and because of that we are going to get the match error.

This is called the pin operator this ^ symbol. It’s called the Pin operator in Elixir and it’s a very useful tool to have because of the way logic is built in Elixir. At the moment, we’re only concerned with the semantics, so the semantics are if you have a variable to the left and there is no Pin operator to it then it’s going to rebound to the value.

If the variable is to the right then it’s not going to rebound and it’s only going to try and match if the match occurs fine. If not you will get a match error. Similarly over here x is to the left and we try to match it if it doesn’t match it tries to rebind it and if we put the Pin operator then only match is going to be tried, and if it doesn’t match we get a match error no rebinding is going to occur.

This is a very powerful concept. Let’s go ahead and put this to use.

Let’s clear this and take a case study. We have a variable a = {:ok , “File Contents”}. The way this works is that whenever you try to open a file and read its contents the return result is going to be a tuple.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

That’s the way Elixir works. If the file was read successfully you get okay in the first element, and the actual contents of the file in the second element. If on the other hand you got an error so you would get this value out. b = {error, “Error Description”}. That’s what you’re going to get back. Notice that these okay and error are atoms so they are going to be returned to you just as they are and then you can work with that. The second thing can be any string that you are working with.

We have a and b over here and what we can do is we can match it, so let’s say we have {:ok, x} = a so what this is going to do is try to match this whole tuple with the value of a and because the value of a is one atom of okay that is going to match with this okay, and whatever is over here whether it’s a string or a number or any other data type that is going to go to X. We hit enter and now because okay matched we can go ahead and read x so x is now file content because x matched with this guy over here. However, if you try to match this guy over here {:error, x} = b. Because this first element in b is an error and you are trying to match this with error it’s going to match, however, if you go over here and change this to {:ok, x} = b this is not going to match.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

Why is that useful? This is useful because in Elixir the general method of passing errors is this guy over here. The return value of a function is going to be a tuple and the first element of that tuple is going to define whether the call was successful or whether there was an error. Let’s go ahead and take a look at a specific example over here. For instance, we have this a over here a = {:ok, “File Contents”}. What we can do is we can make a decision over here and for that, we can have a case statement. A case statement is like a switch statement in C or C++ or Java. We don’t have this in Python but we do have it in Elixir, so let’s take a look at that as well. We say “case a do. “

So between this do and end we are going to have the case block. Over here we can say {:ok, x} ->. I can say {:ok, x} -> “Success: Contents # {x}” . There you go. That’s my first case then I can have {: error, y ->” error #{y}. These are my two cases and then I can also have a default case for that we use underscore and if both of the above ones don’t match then we say -> “Default value”. This is a basic switch case statement and then we say end and there you go.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

Because it was okay and file content this specific case matched and we got the actual contents in x. On the other hand if we have {:error, “File Contents”} and we have the same case statement over here let’s go ahead and reproduce this whole guy, and there you go, and end and now we get an error this first case did not match the second case did.

That’s essentially how you do it. You do a is equal to file read and then you do a = {:error, “File Contents”} and then you do a case. If file was read successfully you execute this block otherwise you execute this block over here {:ok, x} -> “Success Contents # {x}”. Otherwise you execute this block over here {: error, y ->” error #{y}.

This is a very powerful concept in Elixir and is very often used instead of exception handling. If you’re comfortable with Python you would know that if an error comes up reading a file you get an exception, and then you handle the exception you have try-catch blocks. In Elixir, this idea of using cases to handle errors is a lot more common, so that’s the idea of pattern matching and using cases in conjunction with pattern matching to structure your code. We’re going to get back to this when we work with Phoenix but here it suffices if you understand this at the moment.

Another thing that we can do is we can say [head | tail] = [ 1, 2, 4, 6, 8].

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

This is also going to pattern match and what this thing means is that head should be matched with the first element and tail should be matched with the rest of the things.

This is very similar to the hd and tl functions that we saw in the previous videos. hd and tail does match that’s perfectly fine. Head will have value 1 and tail is going to have the rest of the list, so you can use pattern matching in lists as well. Finally, if you don’t want the tail you can say [head | _] = [ 1, 2, 4] and there you go.

That is the idea of pattern matching in Elixir and it’s very often used, and it’s one of the most powerful constructs that are available in an Elixir which are not available in any other language. Please practice with this and get comfortable with it.

Decision Making in Elixir.

Now that we’ve taken a look at the basic data types and some operations on them we can go ahead and look at decision-making so let’s start with the basics.

We have the if statement so if age >= 18 do and within this do we are going to have the if block, so we can return the “Can drive” from over here. You will notice that I’m not putting an IO.puts. I am not putting a return over here. I’m just putting in the string.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

The reason is that in any Elixir statement, whatever the last operation returns, that is the return value. This “can drive” is going to be the return value for this F. We’ll see what this means in a minute. We can also have the else and here you can put “nope” and then end. Between this do and this end block we have a whole if and we can have the else over here as well. Because the age is we have this guy returned over here so this whole if statement returns “Can drive”.

So we can go ahead and change the age = 16 and that is going to mean that our if is going to return a nope. That’s going to return a “Nope”.

We can also skip the else altogether so we can have if age >= 2 “Can drive” and end. That’s it. It returns nil which is the equivalent of none in Python because this if (if age >= 18 do) did not go into the if block and there is no else block so we get a nil back, so that’s the basic if.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

Let’s go ahead and take a look at another decision-making module which is called cond. We have cond do and here we can put any statement, so we can say 2 + 2 == 5 -> “This will never be true” because 2 + 2 = 5. We can have another statement over here age == 16 and that is going to return “Age is 16” or we can have a 1 + 1 == 2 and that is going to be “Yes, 2” then we can say end.

Because how cond works it’s going to check these statements one by one so whenever one of them matches it is going to stop executing the other ones. This guy is going to be false so we’re going to skip this, this becomes true, and this is going to be output because the value of “Age is 16” at the moment, so this is going to be returned. This guy is never going to be executed. So if you do that “Age is 16 and this guy is not executed at all. It’s not quite like the switch statement of C or Java, so you don’t go from top to bottom doing everything. There is an automatic break after whichever statement becomes true. That’s cond.

We’ve already taken a look at the case statement earlier on so you can go back and look at it in the previous section.

Here we take a look at another statement which is highly you need to Elixir. This is called unless so we say unless age > 18 does “You are too young” end.

Because the value of age is, unless it is greater than it becomes false, so unless it is essentially, we can have if age <= 18 do “You are too young”, end. This statement over here, if age <= 18 it’s equivalent to unless it is greater than 18.

You can think of unless as being if and not. Not with an F gives you an unless and it’s a little more readable but I personally find it very difficult to get my head around it, so I try to avoid unless, unless it’s absolutely necessary. That’s decision making in Elixir and in the next section we’re going to move ahead and do something a lot more interesting which is defining modules.

Putting Code in a File in Visual Studio Code.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

Up until now we’ve been working with the Elixir interactive shell but as you would be aware the interactive shell is very limited and we have to do a lot of typing in order to work with it. What we want to do instead is now go ahead and put some code in a file, so let’s open up our editor. I’m using Visual Studio code so you can use any editor that you want.

I’m in my ELIXIR – INTRO folder and I’m going to create a new file and I’m going to call this 00math.ex. You can name it anything but the extension has to be ex for the Elixir executable.

We are going to create a module so it is defmodule and we’re going to call it Math do and end. In between all of this is going to be the definition of the module. We’re going to go ahead and save this. Thinking of a module has been the equivalent of a Python package, so for instance, if you have a Python file you put from math import sqrt or you put import math.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

This math is a module or a package in Python. We have the module math over here. By convention we make the first letter capital and we put this essentially in a toggle case. We have the math module over here. In this math module we can have other modules and we can have functions.

So we’re going to define a very basic function which is going to be called sum. def sum(a, b) end.

In between this we can put any statement that we want. So we’ve taken a look at quite a lot of statements from previous parts of the course. Here you can put anything that you want and remember that the function is going to return the value that is returned by the last statement in the function. You don’t have to have a return statement over here, all you have to do is put a + b and this is essentially going to do the return automatically, so you do not have a return statement in Elixir.

a + b is going to be automatically returned because this is the last statement that is being executed over here.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

Now let’s go ahead and save this file and go back to our terminal. As you can see, we have the file over here, let’s go ahead and start the Elixir shell. Here we can say c(“00math.ex”).

This is going to compile the file and load it and as you can see we have the math module now available. We can say Math.sum(1, 2) and this is going to return the value. This is essentially how Elixir works. You create a .ex file then you compile it and then you use it, but because we are going to experiment a lot with the code it becomes a little difficult to work with this. What we’re going to do instead is define an Elixir script file so let’s hit Ctrl C and get out of this file and let’s go ahead and clear this.

Go back to our editor and this time we are going to create a new file, and we’re going to call it 01mathscript.exs for Elixir script.

You can name it anything that you like but we are but we are putting  01math script so that we can recall this later on. We are going to put the same code so let’s go ahead and copy this and paste this over here. We are going to put IO.puts Math.sum(1,2).

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

There you go. The file has been saved and now we can go back to our terminal and execute it using elixir 01math script.exs. As you can see it’s outputting three so this is a lot easier to work with when you’re experimenting. When you are done with your code, you want to change this to an Elixir.ex file instead of an exs file because a compiled file is a lot faster to work with.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

Let’s go ahead and take a look at some other details which are in our module. So let’s go back to our editor, create a new file, and we are going to put the same code over here, and save this as 02math.exs. By the way I’m going to make all of these files available to you for reference but it’s much better if you type them out yourself as is with any programming language.

We have a sum function over here in this module and we have a defp. What defp does is it defines a private function, so we can have do_sum(a,b) do end. Here we can also put a + b.

Now, if you go ahead and try to call these you can say IO.puts Math.sum(1,2) and that is going to work perfectly fine. However, if I try to do IO.puts Math.sum (1,2) which is a private function, you will see that this is going to give me an error. Let’s say elixir 02math.exs and as you can see this 3 gets output perfectly fine however we get an undefined function error for Math. do_sum/2. T his is either undefined or private. The Elixir runtime doesn’t care which is what you would expect from a private function.

Learn Elixir Programming! Elixir Language Fundaments with Mohammad Nauman

This is how you define modules, this is how you define functions in modules, and this is how you make some functions private. That is some basic intro to modules and in the next section, we are going to take a look at a very powerful concept which is going to merge functions with the concept of pattern matching that we saw in the first couple of sections.

GET MORE OF THIS COURSE

Would you like to continue learning about the Elixir and Phoenix: Real World Functional Programming Course? If you are interested will you please buy the complete course,  Elixir and Phoenix: Real World Functional Programming Course, on the Uthena Education Platform..

You can also get the first 1 hour and 14 minutes of the course completely for free on YouTube.

Thank you for reading the blog post or watching the course on YouTube.

I love you.

You’re awesome.

Thank you very much for checking out the Elixir and Phoenix: Real World Functional Programming Course and I hope to see you again in the next blog post or video.

You may like this post: Java Programming for Beginners from Development Kit Installation to Exceptions

Love,

Jerry Banfield.