Elixir Basic Syntax

Welcome to a tutorial on Basic Syntax on Elixir. Here you will learn a few basic codes such as the 'Hello World' program.

Now, to kick start the Elixir interactive shell, enter the command below.

iex

Once that shell is up, use the IO.puts function to "put" the string on the console output. Enter the code below in your Elixir shell:

IO.puts "Hello world"

The Elixir script mode will be used as we will need to keep the Elixir code in a file with the extension .ex, in this tutorial.

Now, let’s keep the above code in the test.ex file. This will be executed using elixir in the next step:

IO.puts "Hello world"

Let’s try to run the above program as shown below:

$elixirc test.ex

The output of the above code is shown below:

Hello World

Note that in this case, we are calling a function IO.puts to generate a string to our console as output. The IO.puts function can as well be called the way we do in C, C++, Java, and so on., providing arguments in parentheses by following the function name. This is shown;

IO.puts("Hello world") 

 

Comments

Single-line comments usually start with a '#' symbol. There's no multi-line comment, however, you can stack multiple comments. Check out the example below.

#This is a comment

 

Line Endings

In Elixir, there are no required line endings like ';'. But, we can have multiple statements in the same line, by using ';'. Check out the example below.

IO.puts("Hello"); IO.puts("World!")

Output is shown below:

Hello 
World!

 

Identifiers

Identifiers like variables and function names are used to identify a variable, function, and so on. We can name identifiers by starting with a lower case alphabet with numbers, underscores, and upper case letters thereafter. Thus, this naming convention is commonly known as snake_case. Below are some examples of valid identifiers in Elixir:

var1    variable_2   variable_3

Also, note that variables can also be named with a leading underscore, and a value that is not meant to be used must be assigned to _ or a variable starting with an underscore (_).

_variable4_value = 37

 

In addition, Elixir relies on underscores to make functions private to modules. But, when you name a function with a leading underscore in a module, and import that module, this function will not be imported at all.

In later tutorials, we will look at other intricacies related to function naming in Elixir.

 

Reserved Words

The words listed below are reserved and cannot be used as variables, modules, or function names.

Afterandcatchdoinbitsinlist
nilelseendNotorfalse
fninrescuetruewhenxor
__MODULE____FILE____DIR____ENV____CALLER__