DEV Community

Brooklin Myers
Brooklin Myers

Posted on • Edited on

The 20% of Elixir syntax you need to read 80% of Elixir code.

A quick cheat sheet of the most common elixir syntax.

This is a brief guide using the Pareto Principle (80/20 rule) to the most common Elixir syntax you’re going to encounter. If you want a crash course or a quick refresher on common Elixir concepts, then this article is for you.

Elixir

Elixir is a dynamic, functional language for building scalable and maintainable applications.
Elixir leverages the Erlang VM, known for running low-latency, distributed, and fault-tolerant systems. Elixir is successfully used in web development, embedded software, data ingestion, and multimedia processing, across a wide range of industries.
- https://elixir-lang.org/

Getting started with Elixir

Skip this section and move on to data types if you already know how to run elixir code.

You can choose to run elixir using a Repl (an online code editor) by executing .ex files on your computer or in the Interactive Elixir (iex) environment.

Using a Repl

If you’d like to get started with Elixir quickly, you can use a website to run elixir code in a web-based code editor.

  • Open the Elixir Repl

  • Make sure it works by typing the following in the editor and press Run.

IO.puts Hello World
Enter fullscreen mode Exit fullscreen mode

It should look like this:

Running Elixir on your computer

You can also install Elixir onto your computer and then run elixir files (.ex) directly.

  • Install Elixir if you don’t have it already

  • Make a new file called test.ex

  • Write the following in the file:

IO.puts Hello World
Enter fullscreen mode Exit fullscreen mode
  • In your Terminal In the folder with your file, run

    elixir test.ex

You may be using a different editor, but it should look something like this:

Using the Interactive Elixir (iex) environment.

You can open the Interactive Elixir environment to experiment with Elixir code. You must already have Installed Elixir on your machine.

On Mac & Linux run:

# On Mac and Linux run:
iex
# On Windows run:
iex.bat
Enter fullscreen mode Exit fullscreen mode

Data Types

In Elixir will commonly encounter the following data types:

Variables

Variables allow you to store data to be referenced throughout your application. In Elixir, you can define a variable as such:

my_integer = 4
my_float = 4.0
my_string = "Hello"
Enter fullscreen mode Exit fullscreen mode

Variables in Elixir use snake_case. A variable can store any data type; it is not restricted to the examples above.

Comments

Comments in elixir use #. There is no multi-line comment for Elixir.

# comments can be on their own line
5 + 5 # or after your code on the same line.
# but not before, because everything after the # is a comment 5 + 5
Enter fullscreen mode Exit fullscreen mode

String

Strings in elixir are series of Unicode Characters written between double quotes “”.

Writing double-quotes inside of a string

you can put double-quotes inside of a string using backslash \

"a string with \"double quotes\""
Enter fullscreen mode Exit fullscreen mode

String concatenation (adding strings)

"Brooklin" <> " " <> "Myers" # "Brooklin Myers"
Enter fullscreen mode Exit fullscreen mode

String interpolation

Elixir code can execute inside of a string using #{}.

name = "Brooklin"
"Hi #{name}" # Hi Brooklin
"What is 5 + 4? #{5 + 4}." # What is 5 + 4? 9.
Enter fullscreen mode Exit fullscreen mode

The String module

You can access string-related functionality with the built-in String module.

Integer and Float

Elixir provides a variety of mechanisms to operate on integers and floats.

Arithmetic operators

Arithmetic operators allow you to manipulate numbers.

# plus (+)
5 + 5 # 10
# minus (-)
5 - 5 # 0
# multiply (*)
5 * 5 # 25
# divide (/)
5 / 5 # 1
Enter fullscreen mode Exit fullscreen mode

Integer Functions

Elixir provides functions rem and div for working with integer division and remainder.

rem(5, 4) # 1
rem(10, 6) # 4
div(3, 2) # 1 (normally 1.5 with divide /)
div(1, 2) # 0 (normally 0.5 with divide /)
div(8, 3) # 2 (normally 2.6666 with divide /)
Enter fullscreen mode Exit fullscreen mode

Booleans

Booleans are true/false values.

and, or, not

Used to compare booleans only:

true and true # true
true and false # false
true or false # true
false or false # false
false or not false # true
true and not true # false
Enter fullscreen mode Exit fullscreen mode

Comparison Operators

Comparison operators are used to compare values. They are commonly used to compare integers and floats but can also be used to compare other data types for sorting purposes.

exactly equals ===

5 === 5   # true
5 === 5.0 # false
4 === 5   # false
4 === "4" # false
Enter fullscreen mode Exit fullscreen mode

equals ==

5 == 5   # true
5 == 5.0 # true
4 == "4" # false, equals still checks type unlike some languages.
Enter fullscreen mode Exit fullscreen mode

not exactly equals !==

5 !== 5   # false
5 !== 5.0 # true
4 !== 5   # true
Enter fullscreen mode Exit fullscreen mode

not equals !=

5 != 5   # false
5 != 5.0 # false
5 != 4   # true
Enter fullscreen mode Exit fullscreen mode

greater than >

4 > 5 # false
5 > 5 # false
6 > 5 # true
Enter fullscreen mode Exit fullscreen mode

less than <

4 < 5 # true
5 < 5 # false
6 < 5 # false
Enter fullscreen mode Exit fullscreen mode

greater than or equal (>=)

4 >= 5 # false
5 >= 5 # true
6 >= 5 # true
Enter fullscreen mode Exit fullscreen mode

less than or equal ≤

4 <= 5 # true
5 <= 5 # true
6 <= 5 # false
Enter fullscreen mode Exit fullscreen mode

Value Comparison: or (||), and (&&), not (!)

You can use this to compare any data types. Anything other than false and nil will evaluate as true. This means even 0 will be evaluated as true. It’s important to remember the returned value is not a boolean. The returned value is the actual value evaluated.

1 && 1           # 1
1 && false       # false
1 || false       # 1
nil || false     # false
false || !nil    # true
1 && "hey"       # "hey"
"hey" && 1       # 1
"hey" || "hello" # "hey"
Enter fullscreen mode Exit fullscreen mode

Atom

Atoms are constants whose value is their own name. They are often used to represent distinct values important to your application. They are often used for handling the state of an operation such as :ok and :error.

    :ok
Enter fullscreen mode Exit fullscreen mode

true, false, and nil are all atoms which Elixir allows you to skip the leading colon (:).

:true === true   # true
:false === false # true
:nil === nil     # true
Enter fullscreen mode Exit fullscreen mode

List

Lists in Elixir are implemented as linked lists. Linked lists hold zero, one, or more elements in the chosen order.

Add and Subtract lists with ++ and --

The List Module

You can access list-related functionality with the built-in List module.


Elixir lists are linked lists, so you can access the head (first element of the list) and the tail (the rest of the list)

Tuple

Use tuples when you want to store a fixed number of elements. Do not use Tuples when you want to iterate through elements as it does not support Enum operations.

A common use of Tuples would be to store known values in an expected order. For example, you might have a tuple for a user with {name, age, city}

{"Brooklin", 23, "Montreal"}
Enter fullscreen mode Exit fullscreen mode

The Tuple module

You can access tuple-related functionality with the built-in Tuple module.

Map

Maps are a key-value data structure in Elixir. The keys in a map must be unique, unlike with key-value lists.

Dot notation

You can access map values using dot notation.

my_map = %{"key" => "value"}
my_map.key # value
Enter fullscreen mode Exit fullscreen mode

Dot notation can throw non_existing_key errors

map.non_existing_key **** (KeyError) key :non_existing_key not found in: %{"key" => "value"}**
Enter fullscreen mode Exit fullscreen mode

The Map module

You can access map-related functionality with the built-in Map module.

For example, you can avoid the non_existing_key error above by using Map.get:

Map update syntax

You can use a special syntax to update map keys. You can only update existing keys.

The Enum module

When iterating over data, usually a list, you can use the Enum module provided by Elixir. lists, ranges, and maps all work with the Enum module.

Conditional statements

Conditional statements are used for branching logic in your application.

if/else

unless/else

Ternary

Ternary is a handy shorthand for if/else statements.

case

case takes in a value and executes a different path in the case statement depending on the value. It may be helpful to relate case to switch-case statements found in other languages.

Variables in a case statement

You can use variables to represent values in the case argument. See n in this example:

cond

cond executes the code for the first true condition. It is a lot like case, except instead of evaluating a single value and executing the path that matches the value, you can define various conditions, making this conditional statement much more versatile at the possible expense of clarity.

Modules and functions

Modules provide a way to organize the behavior of your program. For example, you might have a Greeting module with a say_hello function to return “Hello”.

How to create a module and function


You’ll notice that modules are CapitalCase and functions are snake_case.

Calling a function

Greeting.say_hello() # Hello
Enter fullscreen mode Exit fullscreen mode

Calling a function from inside the same module

You do not have to reference the Module when calling a function from inside the same module. So Greeting.say_hello becomes say_hello.

Functions with different parameters

One really cool feature of Elixir is to treat two functions with the same name but different parameters as two different functions. For example, the Greeting.say_hello function can be referred to as say_hello/0. 0 because it didn’t take any parameters.

A function that returns a boolean should end with a question mark (?)

Default Arguments

Elixir supports default arguments using \

Brackets are optional

Use brackets when you think it adds to the clarity of the code, or don’t!

Handling functions with context using when

You can use when syntax to say what should happen under a specific condition.


The order of your functions matters, as the first function to be true always runs first. Here’s an example of when used with the wrong function order.

Reusing Modules

Elixir provides directives for reusing modules in your project.

It’s important to note that Elixir is a compiled language. It is usually compiled using a tool called mix. So unlike a language like Javascript or Ruby, you do not import one file into another. Instead, modules are compiled together and can be accessed from any .ex files in the project.

Alias

alias allows you to import a module into another module and access it using a different name. This is commonly used to access nested modules more conveniently.

import

import is used to conveniently access functions from other modules.

For example, here is how you would access the puts/1 function from the IO module.

use

use allows you to inject functionality from one module into another.

Initially, you will most often use…use… 😅 with modules from third parties. For example, to write tests with the ExUnit framework, you will use the ExUnit.Case module


use is a reasonably complicated topic, and it’s good enough if you understand it at a surface level early on. For further reading, see an elixirschool tutorial on use or read the documentation.

Pipe

Elixir allows you to pass the return value of a function into another using pipe syntax (|>)

Pattern Matching

In Elixir, the = symbol is called the match operator. It is useful for assigning simple values, or it can also destructure more complex data types.

{name, age, city} = {"Brooklin", 23, "Montreal"} # using a tuple
[a, b, c] = [1, 2, 3] # using a list
[head | tail] = [1, 2, 3] # you saw this before with lists
Enter fullscreen mode Exit fullscreen mode

MatchError

If your destructuring doesn’t match the right-hand side value, you will get a MatchError

{a, b, c} **=** {:hello, "world"}
    ****** (MatchError) no match of right hand side value: {:hello, "world"}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Hopefully, this article helps you rapidly get familiar with some of the most important bits of Elixir.

I left out a lot to keep the article concise. To learn more, the Elixir Documentation is a great place to start.

Please comment if you notice any inaccuracies or if you think there’s some other Elixir syntax I should have covered. You’ll be helping me and everyone else reading this!

Top comments (7)

Collapse
 
foolonthehill profile image
George Oliveira

Excellent post!

Collapse
 
goarango profile image
G.O. Arango

Muy simple y claro.

Collapse
 
belgoros profile image
Serguei Cambour • Edited

Thank you for sharing and wrapping it out! Is it a wrong copy/paste or intentional, - you used the same code snippets both for String and Map module ? (see below):

# with string syntax
map = %{"key" => "value"}
Map.get(map, "key") # value

# with atom syntax
map = %{key: "value"}
Map.get(map, :key) # value
Enter fullscreen mode Exit fullscreen mode
Collapse
 
pystar profile image
Pystar

Great writeup of a Birdseye view of the Elixir language. Can you do Phoenix?

Collapse
 
brooklinmyers profile image
Brooklin Myers

Thank you, great idea!

Collapse
 
t0nghe profile image
Tonghe Wang

Great post! Thanks for summarizing this great post and sharing it here. It helps a lot!

Collapse
 
robsonbbs profile image
Robson Barreto

I have to touch the elixir code now and then so every time I have to do it I forget most of these concepts 😅 This article was great to recap!