Skip to content

Instantly share code, notes, and snippets.

@sshkarupa
Created November 4, 2018 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sshkarupa/81215455c13d175476ec35e47dfb1658 to your computer and use it in GitHub Desktop.
Save sshkarupa/81215455c13d175476ec35e47dfb1658 to your computer and use it in GitHub Desktop.
Elixir cheat sheet

Elixir Cheat Sheet

Getting started

Hello world

# hello.exs
defmodule Greeter do
  def greet(name) do
    message = "Hello, " <> name <> "!"
    IO.puts message
  end
end

Greeter.greet("world")
elixir hello.exs
# Hello, world!

Variables

age = 23

Maps

user = %{
  name: "John",
  city: "Melbourne"
}
IO.puts "Hello, " <> user.name

Lists

users = [ "Tom", "Dick", "Harry" ]
Enum.map(users, fn user ->
  IO.puts "Hello " <> user
end)

Piping

source
|> transform(:hello)
|> print()
# Same as:
print(transform(source, :hello))

These two are equivalent.

Pattern matching

user = %{name: "Tom", age: 23}
%{name: username} = user

This sets username to "Tom".

Pattern matching in functions

def greet(%{name: username}) do
  IO.puts "Hello, " <> username
end

user = %{name: "Tom", age: 23}

Pattern matching works in function parameters too.

Control flow

If

if false do
  "This will never be seen"
else
  "This will"
end

Case

case {1, 2, 3} do
  {4, 5, 6} ->
    "This clause won't match"
  {1, x, 3} ->
    "This will match and bind x to 2"
  _ ->
   "This will match any value"
end

Cond

cond do
  1 + 1 == 3 ->
    "I will never be seen"
  2 * 5 == 12 ->
    "Me neither"
  true ->
    "But I will (this is essentially an else)"
end

Errors

try do
  throw(:hello)
catch
  message -> "Got #{message}."
after
  IO.puts("I'm the after clause.")
end

Types

Primitives

Sample Type
nil Nil/null
true / false Boolean
--- ---
?a Integer (ASCII)
23 Integer
3.14 Float
--- ---
'hello' Charlist
<<2, 3>> Binary
"hello" Binary string
:hello Atom
--- ---
[a, b] List
{a, b} Tuple
--- ---
%{a: "hello"} Map
%MyStruct{a: "hello"} Struct
fn -> ... end Function

Type checks

is_atom/1
is_bitstring/1
is_boolean/1
is_function/1
is_function/2
is_integer/1
is_float/1
is_binary/1
is_list/1
is_map/1
is_tuple/1
is_nil/1
is_number/1
is_pid/1
is_port/1
is_reference/1

Operators

left != right   # equal
left !== right  # match
left ++ right   # concat lists
left <> right   # concat string/binary
left =~ right   # regexp

Modules

Importing

require Redux   # compiles a module
import Redux    # compiles, and you can use without the `Redux.` prefix

use Redux       # compiles, and runs Redux.__using__/1
use Redux, async: true

import Redux, only: [duplicate: 2]
import Redux, only: :functions
import Redux, only: :macros

import Foo.{Bar, Baz}

Aliases

alias Foo.Bar, as: Bar
alias Foo.Bar   # same as above

alias Foo.{Bar, Baz}

String

Functions

import String
str = "hello"
str |> length()        # → 5
str |> codepoints()    # → ["h", "e", "l", "l", "o"]
str |> slice(2..-1)    # → "llo"
str |> split(" ")      # → ["hello"]
str |> capitalize()    # → "Hello"
str |> match(regex)

Inspecting objects

inspect(object, opts \\ [])
value |> IO.inspect()
value |> IO.inspect(label: "value")

Numbers

Operations

abs(n)
round(n)
rem(a, b)   # remainder (modulo)
div(a, b)   # integer division

Float

import Float
n = 10.3
n |> ceil()            # → 11.0
n |> ceil(2)           # → 11.30
n |> to_string()       # → "1.030000+e01"
n |> to_string([decimals: 2, compact: true])
Float.parse("34")  # → { 34.0, "" }

Integer

import Integer
n = 12
n |> digits()         # → [1, 2]
n |> to_charlist()    # → '12'
n |> to_string()      # → "12"
n |> is_even()
n |> is_odd()
# Different base:
n |> digits(2)        # → [1, 1, 0, 0]
n |> to_charlist(2)   # → '1100'
n |> to_string(2)     # → "1100"
parse("12")           # → {12, ""}
undigits([1, 2])      # → 12

Type casting

Float.parse("34.1")    # → {34.1, ""}
Integer.parse("34")    # → {34, ""}
Float.to_string(34.1)  # → "3.4100e+01"
Float.to_string(34.1, [decimals: 2, compact: true])  # → "34.1"

Map

Defining

m = %{name: "hi"}       # atom keys (:name)
m = %{"name" => "hi"}   # string keys ("name")

Updating

import Map
m = %{m | name: "yo"}  # key must exist
m |> put(:id, 2)      # → %{id: 2, name: "hi"}
m |> put_new(:id, 2)  # only if `id` doesn't exist (`||=`)
m |> put(:b, "Banana")
m |> merge(%{b: "Banana"})
m |> update(:a, &(&1 + 1))
m |> update(:a, fun a -> a + 1 end)
m |> get_and_update(:a, &(&1 || "default"))
# → {old, new}

Deleting

m |> delete(:name)  # → %{}
m |> pop(:name)     # → {"John", %{}}

Reading

m |> get(:id)       # → 1
m |> keys()         # → [:id, :name]
m |> values()       # → [1, "hi"]
m |> to_list()      # → [id: 1, name: "hi"]
                    # → [{:id, 1}, {:name, "hi"}]

Deep

put_in(map, [:b, :c], "Banana")
put_in(map[:b][:c], "Banana")    # via macros
get_and_update_in(users, ["john", :age], &{&1, &1 + 1})

Constructing from lists

Map.new([{:b, 1}, {:a, 2}])
Map.new([a: 1, b: 2])
Map.new([:a, :b], fn x -> {x, x} end)  # → %{a: :a, b: :b}

List

import List
l = [ 1, 2, 3, 4 ]
l = l ++ [5]         # push (append)
l = [ 0 | list ]     # unshift (prepend)
l |> first()
l |> last()
l |> flatten()
l |> flatten(tail)

Also see Enum.

Enum

Usage

import Enum
list = [:a, :b, :c]
list |> at(0)         # → :a
list |> count()       # → 3
list |> empty?()      # → false
list |> any?()        # → true
list |> concat([:d])  # → [:a, :b, :c, :d]

Also, consider streams instead.

Map/reduce

list |> reduce(fn)
list |> reduce(acc, fn)
list |> map(fn)
list |> reject(fn)
list |> any?(fn)
list |> empty?(fn)
[1, 2, 3, 4]
|> Enum.reduce(0, fn(x, acc) -> x + acc end)

Tuple

Tuples

import Tuple
t = { :a, :b }
t |> elem(1)    # like tuple[1]
t |> put_elem(index, value)
t |> tuple_size()

Keyword lists

list = [{ :name, "John" }, { :age, 15 }]
list[:name]
# For string-keyed keyword lists
list = [{"size", 2}, {"type", "shoe"}]
List.keyfind(list, "size", 0)  # → {"size", 2}

Functions

Lambdas

square = fn n -> n*n end
square.(20)

& syntax

square = &(&1 * &1)
square.(20)

square = &Math.square/1

Running

fun.(args)
apply(fun, args)
apply(module, fun, args)

Function heads

def join(a, b \\ nil)
def join(a, b) when is_nil(b) do: a
def join(a, b) do: a <> b

Structs

Structs

defmodule User do
  defstruct name: "", age: nil
end

%User{name: "John", age: 20}

%User{}.struct  # → User

See: Structs

Protocols

Defining protocols

defprotocol Blank do
  @doc "Returns true if data is considered blank/empty"
  def blank?(data)
end
defimpl Blank, for: List do
  def blank?([]), do: true
  def blank?(_), do: false
end

Blank.blank?([])  # → true

Any

defimpl Blank, for: Any do ... end

defmodule User do
  @derive Blank     # Falls back to Any
  defstruct name: ""
end

Examples

  • Enumerable and Enum.map()
  • Inspect and inspect()

Comprehensions

For

for n <- [1, 2, 3, 4], do: n * n
for n <- 1..4, do: n * n
for {key, val} <- %{a: 10, b: 20}, do: val
# → [10, 20]
for {key, val} <- %{a: 10, b: 20}, into: %{}, do: {key, val*val}

Conditions

for n <- 1..10, rem(n, 2) == 0, do: n
# → [2, 4, 6, 8, 10]

Complex

for dir <- dirs,
    file <- File.ls!(dir),          # nested comprehension
    path = Path.join(dir, file),    # invoked
    File.regular?(path) do          # condition
  IO.puts(file)
end

Misc

Metaprogramming

__MODULE__
__MODULE__.__info__

@after_compile __MODULE__
def __before_compile__(env)
def __after_compile__(env, _bytecode)
def __using__(opts)    # invoked on `use`

@on_definition {__MODULE__, :on_def}
def on_def(_env, kind, name, args, guards, body)

@on_load :load_check
def load_check

Regexp

exp = ~r/hello/
exp = ~r/hello/i
"hello world" =~ exp

Sigils

~r/regexp/
~w(list of strings)
~s|strings with #{interpolation} and \x20 escape codes|
~S|no interpolation and no escapes|
~c(charlist)

Allowed chars: / | " ' ( [ { < """. See: Sigils

Type specs

@spec round(number) :: integer

@type number_with_remark :: {number, String.t}
@spec add(number, number) :: number_with_remark

Useful for dialyzer. See: Typespecs

Behaviours

defmodule Parser do
  @callback parse(String.t) :: any
  @callback extensions() :: [String.t]
end
defmodule JSONParser do
  @behaviour Parser

  def parse(str), do: # ... parse JSON
  def extensions, do: ["json"]
end

See: Module

References

# Single line comments start with a number symbol.
# There's no multi-line comment,
# but you can stack multiple comments.
# To use the elixir shell use the `iex` command.
# Compile your modules with the `elixirc` command.
# Both should be in your path if you installed elixir correctly.
## ---------------------------
## -- Basic types
## ---------------------------
# There are numbers
3 # integer
0x1F # integer
3.0 # float
# Atoms, that are literals, a constant with name. They start with `:`.
:hello # atom
# Tuples that are stored contiguously in memory.
{1,2,3} # tuple
# We can access a tuple element with the `elem` function:
elem({1, 2, 3}, 0) #=> 1
# Lists that are implemented as linked lists.
[1,2,3] # list
# We can access the head and tail of a list as follows:
[head | tail] = [1,2,3]
head #=> 1
tail #=> [2,3]
# In elixir, just like in Erlang, the `=` denotes pattern matching and
# not an assignment.
#
# This means that the left-hand side (pattern) is matched against a
# right-hand side.
#
# This is how the above example of accessing the head and tail of a list works.
# A pattern match will error when the sides don't match, in this example
# the tuples have different sizes.
# {a, b, c} = {1, 2} #=> ** (MatchError) no match of right hand side value: {1,2}
# There are also binaries
<<1,2,3>> # binary
# Strings and char lists
"hello" # string
'hello' # char list
# Multi-line strings
"""
I'm a multi-line
string.
"""
#=> "I'm a multi-line\nstring.\n"
# Strings are all encoded in UTF-8:
"héllò" #=> "héllò"
# Strings are really just binaries, and char lists are just lists.
<<?a, ?b, ?c>> #=> "abc"
[?a, ?b, ?c] #=> 'abc'
# `?a` in elixir returns the ASCII integer for the letter `a`
?a #=> 97
# To concatenate lists use `++`, for binaries use `<>`
[1,2,3] ++ [4,5] #=> [1,2,3,4,5]
'hello ' ++ 'world' #=> 'hello world'
<<1,2,3>> <> <<4,5>> #=> <<1,2,3,4,5>>
"hello " <> "world" #=> "hello world"
# Ranges are represented as `start..end` (both inclusive)
1..10 #=> 1..10
lower..upper = 1..10 # Can use pattern matching on ranges as well
[lower, upper] #=> [1, 10]
# Maps are key-value pairs
genders = %{"david" => "male", "gillian" => "female"}
genders["david"] #=> "male"
# Maps with atom keys can be used like this
genders = %{david: "male", gillian: "female"}
genders.gillian #=> "female"
## ---------------------------
## -- Operators
## ---------------------------
# Some math
1 + 1 #=> 2
10 - 5 #=> 5
5 * 2 #=> 10
10 / 2 #=> 5.0
# In elixir the operator `/` always returns a float.
# To do integer division use `div`
div(10, 2) #=> 5
# To get the division remainder use `rem`
rem(10, 3) #=> 1
# There are also boolean operators: `or`, `and` and `not`.
# These operators expect a boolean as their first argument.
true and true #=> true
false or true #=> true
# 1 and true
#=> ** (BadBooleanError) expected a boolean on left-side of "and", got: 1
# Elixir also provides `||`, `&&` and `!` which accept arguments of any type.
# All values except `false` and `nil` will evaluate to true.
1 || true #=> 1
false && 1 #=> false
nil && 20 #=> nil
!true #=> false
# For comparisons we have: `==`, `!=`, `===`, `!==`, `<=`, `>=`, `<` and `>`
1 == 1 #=> true
1 != 1 #=> false
1 < 2 #=> true
# `===` and `!==` are more strict when comparing integers and floats:
1 == 1.0 #=> true
1 === 1.0 #=> false
# We can also compare two different data types:
1 < :hello #=> true
# The overall sorting order is defined below:
# number < atom < reference < functions < port < pid < tuple < list < bit string
# To quote Joe Armstrong on this: "The actual order is not important,
# but that a total ordering is well defined is important."
## ---------------------------
## -- Control Flow
## ---------------------------
# `if` expression
if false do
"This will never be seen"
else
"This will"
end
# There's also `unless`
unless true do
"This will never be seen"
else
"This will"
end
# Remember pattern matching? Many control-flow structures in elixir rely on it.
# `case` allows us to compare a value against many patterns:
case {:one, :two} do
{:four, :five} ->
"This won't match"
{:one, x} ->
"This will match and bind `x` to `:two` in this clause"
_ ->
"This will match any value"
end
# It's common to bind the value to `_` if we don't need it.
# For example, if only the head of a list matters to us:
[head | _] = [1,2,3]
head #=> 1
# For better readability we can do the following:
[head | _tail] = [:a, :b, :c]
head #=> :a
# `cond` lets us check for many conditions at the same time.
# Use `cond` instead of nesting many `if` expressions.
cond do
1 + 1 == 3 ->
"I will never be seen"
2 * 5 == 12 ->
"Me neither"
1 + 2 == 3 ->
"But I will"
end
# It is common to set the last condition equal to `true`, which will always match.
cond do
1 + 1 == 3 ->
"I will never be seen"
2 * 5 == 12 ->
"Me neither"
true ->
"But I will (this is essentially an else)"
end
# `try/catch` is used to catch values that are thrown, it also supports an
# `after` clause that is invoked whether or not a value is caught.
try do
throw(:hello)
catch
message -> "Got #{message}."
after
IO.puts("I'm the after clause.")
end
#=> I'm the after clause
# "Got :hello"
## ---------------------------
## -- Modules and Functions
## ---------------------------
# Anonymous functions (notice the dot)
square = fn(x) -> x * x end
square.(5) #=> 25
# They also accept many clauses and guards.
# Guards let you fine tune pattern matching,
# they are indicated by the `when` keyword:
f = fn
x, y when x > 0 -> x + y
x, y -> x * y
end
f.(1, 3) #=> 4
f.(-1, 3) #=> -3
# Elixir also provides many built-in functions.
# These are available in the current scope.
is_number(10) #=> true
is_list("hello") #=> false
elem({1,2,3}, 0) #=> 1
# You can group several functions into a module. Inside a module use `def`
# to define your functions.
defmodule Math do
def sum(a, b) do
a + b
end
def square(x) do
x * x
end
end
Math.sum(1, 2) #=> 3
Math.square(3) #=> 9
# To compile our simple Math module save it as `math.ex` and use `elixirc`
# in your terminal: elixirc math.ex
# Inside a module we can define functions with `def` and private functions with `defp`.
# A function defined with `def` is available to be invoked from other modules,
# a private function can only be invoked locally.
defmodule PrivateMath do
def sum(a, b) do
do_sum(a, b)
end
defp do_sum(a, b) do
a + b
end
end
PrivateMath.sum(1, 2) #=> 3
# PrivateMath.do_sum(1, 2) #=> ** (UndefinedFunctionError)
# Function declarations also support guards and multiple clauses.
# When a function with multiple clauses is called, the first function
# that satisfies the clause will be invoked.
# Example: invoking area({:circle, 3}) will call the second area
# function defined below, not the first:
defmodule Geometry do
def area({:rectangle, w, h}) do
w * h
end
def area({:circle, r}) when is_number(r) do
3.14 * r * r
end
end
Geometry.area({:rectangle, 2, 3}) #=> 6
Geometry.area({:circle, 3}) #=> 28.25999999999999801048
# Geometry.area({:circle, "not_a_number"})
#=> ** (FunctionClauseError) no function clause matching in Geometry.area/1
# Due to immutability, recursion is a big part of elixir
defmodule Recursion do
def sum_list([head | tail], acc) do
sum_list(tail, acc + head)
end
def sum_list([], acc) do
acc
end
end
Recursion.sum_list([1,2,3], 0) #=> 6
# Elixir modules support attributes, there are built-in attributes and you
# may also add custom ones.
defmodule MyMod do
@moduledoc """
This is a built-in attribute on a example module.
"""
@my_data 100 # This is a custom attribute.
IO.inspect(@my_data) #=> 100
end
# The pipe operator |> allows you to pass the output of an expression
# as the first parameter into a function.
Range.new(1,10)
|> Enum.map(fn x -> x * x end)
|> Enum.filter(fn x -> rem(x, 2) == 0 end)
#=> [4, 16, 36, 64, 100]
## ---------------------------
## -- Structs and Exceptions
## ---------------------------
# Structs are extensions on top of maps that bring default values,
# compile-time guarantees and polymorphism into Elixir.
defmodule Person do
defstruct name: nil, age: 0, height: 0
end
joe_info = %Person{ name: "Joe", age: 30, height: 180 }
#=> %Person{age: 30, height: 180, name: "Joe"}
# Access the value of name
joe_info.name #=> "Joe"
# Update the value of age
older_joe_info = %{ joe_info | age: 31 }
#=> %Person{age: 31, height: 180, name: "Joe"}
# The `try` block with the `rescue` keyword is used to handle exceptions
try do
raise "some error"
rescue
RuntimeError -> "rescued a runtime error"
_error -> "this will rescue any error"
end
#=> "rescued a runtime error"
# All exceptions have a message
try do
raise "some error"
rescue
x in [RuntimeError] ->
x.message
end
#=> "some error"
## ---------------------------
## -- Concurrency
## ---------------------------
# Elixir relies on the actor model for concurrency. All we need to write
# concurrent programs in elixir are three primitives: spawning processes,
# sending messages and receiving messages.
# To start a new process we use the `spawn` function, which takes a function
# as argument.
f = fn -> 2 * 2 end #=> #Function<erl_eval.20.80484245>
spawn(f) #=> #PID<0.40.0>
# `spawn` returns a pid (process identifier), you can use this pid to send
# messages to the process. To do message passing we use the `send` operator.
# For all of this to be useful we need to be able to receive messages. This is
# achieved with the `receive` mechanism:
# The `receive do` block is used to listen for messages and process
# them when they are received. A `receive do` block will only
# process one received message. In order to process multiple
# messages, a function with a `receive do` block must recursively
# call itself to get into the `receive do` block again.
defmodule Geometry do
def area_loop do
receive do
{:rectangle, w, h} ->
IO.puts("Area = #{w * h}")
area_loop()
{:circle, r} ->
IO.puts("Area = #{3.14 * r * r}")
area_loop()
end
end
end
# Compile the module and create a process that evaluates `area_loop` in the shell
pid = spawn(fn -> Geometry.area_loop() end) #=> #PID<0.40.0>
# Alternatively
pid = spawn(Geometry, :area_loop, [])
# Send a message to `pid` that will match a pattern in the receive statement
send pid, {:rectangle, 2, 3}
#=> Area = 6
# {:rectangle,2,3}
send pid, {:circle, 2}
#=> Area = 12.56000000000000049738
# {:circle,2}
# The shell is also a process, you can use `self` to get the current pid
self() #=> #PID<0.27.0>
## ---------------------------
## -- Agents
## ---------------------------
# An agent is a process that keeps track of some changing value
# Create an agent with `Agent.start_link`, passing in a function
# The initial state of the agent will be whatever that function returns
{ok, my_agent} = Agent.start_link(fn -> ["red", "green"] end)
# `Agent.get` takes an agent name and a `fn` that gets passed the current state
# Whatever that `fn` returns is what you'll get back
Agent.get(my_agent, fn colors -> colors end) #=> ["red", "green"]
# Update the agent's state the same way
Agent.update(my_agent, fn colors -> ["blue" | colors] end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment