Elixir Examples
Elixir Examples
All Examples
Documentation:
Kernel.get_in/2
Sum an enumerable
This example shows how to sum a list, map, range, or other enumerable to calculate a total value.
6 == Enum.sum([1, 2, 3])
6 == Enum.sum(1..3)
Documentation:
Enum.sum/1
Enum.reduce/3
defmodule User do
end
# dot syntax
%User{email: "c@c.com"}[:email]
#** (UndefinedFunctionError) undefined function User.fetch/2 (User does not implement the
# User.fetch(%User{email: "c@c.com"}, :email)
Documentation:
Structs
defmodule User do
end
Documentation:
Structs
Kernel.struct/2
1 = [a: 1, b: 2, a: 3][:a]
[a: 1, b: 2, a: 3].a
Documentation: Keyword
%{a: 1, b: 2}
Use and or or when you have boolean inputs and want a boolean result.
Behaviours
Behaviours provide a way to define an interface which a module can implement. A module declares that
it implements the Behaviour with the @behaviour annotation. The functions in the modules
implementing the behaviour will be checked at compile time to see if they match the function
specifications in the behavior.
defmodule Greeter do
end
defmodule NormalGreeter do
@behaviour Greeter
end
defmodule ExcitedGreeter do
@behaviour Greeter
end
defmodule InvalidGreeter do
@behaviour Greeter
end
Documentation: Behaviours
HTTP Request
Cowboy
Plug
Phoenix Endpoint
Phoenix Router
Phoenix Controller
Phoenix View
Phoenix Template
HTTP Response
HTTP Request
A browser user sends an HTTP GET request to http://localhost:4000/ .
Cowboy
Cowboy is an Erlang based HTTP server which is currently the only server with a Plug adapter
implemented.
Cowboy will parse the HTTP request and the first Plug Connection will be created in Plug’s Cowboy
adapter.
Plug
Plug is a web server interface for Elixir that provides a way to compose modules in a sequence during a
request/response cycle.
Each plug module receives the HTTP request which is called a Plug Connection and often referred to as
the variable conn . The plug may transform and update the connection and then return an HTTP
response immediately or pass the connection to the next plug in the sequence.
The Plug library has built in plugs that provide CSRF protection, sessions, logging, serving static files, and
more.
Phoenix applications themselves are built by composing a series of plugs which are defined in a Phoenix
Endpoint.
Phoenix Endpoint
The Phoenix Endpoint is found in the project file lib/hello_world/endpoint.ex . The endpoint defines
the plugs that will make up your application. It is the entry and exit point to the Phoenix application.
Each plug will be called in order as defined in the HelloWorld.Endpoint . A plug such as the
Plug.Static plug may send a response before the connection is seen by other plugs. Note that the
last plug defined is the router.
defmodule HelloWorld.Endpoint do
plug Plug.Static,
if code_reloading? do
plug Phoenix.LiveReloader
plug Phoenix.CodeReloader
end
plug Plug.Logger
plug Plug.Parsers,
pass: ["*/*"],
json_decoder: Poison
plug Plug.MethodOverride
plug Plug.Head
plug Plug.Session,
store: :cookie,
key: "_hello_world_key",
signing_salt: "0yg9mHDO"
end
Phoenix Router
A Router defines an application’s pipelines and paths. If the given URL path matches based on the HTTP
verb and path, the indicated controller action will be run.
Pipelines are defined using the pipeline macro which describes a sequence of plugs to run on the
connection. The scope macros define which pipelines to run using the pipe_through macro.
In this example, our GET request to http://localhost:4000/ will match get "/" definition so the
PageController.index function will be called after the :browser pipeline plugs are called with the
connection. The :browser pipeline is called because the get "/" is defined inside a scope that
specifies a pipeline using pipe_through .
The Phoenix Router is analogous to the routes.rb file in Ruby on Rails. The mix phoenix.routes
command will list the routes and path helpers defined by the router.
defmodule HelloWorld.Router do
pipeline :browser do
plug :fetch_session
plug :fetch_flash
plug :protect_from_forgery
end
pipeline :api do
end
end
# pipe_through :api
# end
end
Phoenix Controller
The controller is where application logic is done. Often this will include running SQL queries using the
Ecto database library which is not covered in this article.
The params variable will contain a string keyed map of request parameters. Next,
Phoenix.Controller.render/2 is called with the conn and template name index.html . Often,
Phoenix.Controller.render/3 will be called with additional data to render like this: render conn,
"index.html", [data: "data"] .
The Phoenix.Controller.render/2 method will lookup the template file which by convention should
be located in web/templates/page/index.html.eex and will then call the
Phoenix.View.render_to_iodata/3 function.
defmodule HelloWorld.PageController do
plug :action
end
end
Phoenix View
Aside from rendering the template, the view also can provide helper functions and path helpers which
will automatically be available to the template.
defmodule HelloWorld.PageView do
end
Phoenix Template
By default, an html formatted EEx template was generated. EEx means Embedded Elixir which allows Elixir
code to be included in template files.
The index.html.eex file that was generated only contains html by default. So, an alternative template
example is shown here.
<div>
</div>
HTTP Response
After the view renders the template, the controller will then call the Plug send_resp method with the
rendered template data to return the HTTP response.
Links
Phoenix Framework
Plug
Cowboy
Ecto
Documentation: File.write/3
head = 1
tail = [2, 3]
[head|tail] = [1]
head = 1
tail = []
[] = []
[head|tail] = []
[1 | tail ]= [1, 2, 3]
tail = [2, 3]
[head | _ ]= [1, 2, 3]
Pipe operator
The pipe operator |> is used to chain together a sequence of function calls. The result of the expression
on the left side of the operator is passed as the first argument to the function in the right side of the
operator.
Alias
Used to shorten the references to a specific module.
%Application.User{}
# After aliasing
%User{}
alias Application.User
# is the same as
Use
Adds functionality to the current module by calling another module’s __using__ macro.
defmodule Hello do
defmacro __using__(_opts) do
quote do
def say_hello do
IO.puts "Hello"
end
end
end
end
defmodule MyModule do
use Hello
end
# prints "Hello"
MyModule.say_hello
Import
Imports specific functions into the current module so they can be called without using their module
name.
"ABC" = String.upcase("abc")
"ABC" = upcase("abc")
import String
Require
Makes a macro from an external module available to the compiler at compile time.
defmodule Hello do
defmacro hello_macro do
quote do
def say_hello do
IO.puts "Hello"
end
end
end
end
defmodule MyModule do
# (CompileError) iex:37: you must require Hello before invoking the macro Hello.hello_m
require Hello
Hello.hello_macro
end
# Prints Hello
MyModule.say_hello
$ mix help
mix hex.outdated # Shows outdated Hex deps for the current project
nil = List.last([])
Documentation: List.last/1
Pin operator
The normal behavior of the match operator is to rebind variables on the left side of the operator if there
is a match. The pin operator ^ is used on the left side of the match operator when you don’t wish to
rebind and would like to match against the value of the pinned variable.
a = 1
# rebind a to 2, then 3
a = 2
a = 3
^a = 4
Function capturing
Elixir often refers to functions in the format Module.function/arity . For example the to_atom
function in the String module which takes one argument would be referred to as String.to_atom/1
in the documentation. When a reference to a function is needed, we can use the function capture syntax,
using the capture operator & , as shown below to get a reference to a function.
fun_to_atom = &String.to_atom/1
:a = fun_to_atom.("a")
true = is_function(fun_to_atom)
# to another function
The capture operator & can also be used to create anonymous functions.
Define a Protocol
A Protocol is a way to dispatch to a particular implementation of a function based on the type of the
parameter.
The macros defprotocol and defimpl are used to define Protocols and Protocol implementations for
different types in the following example.
defprotocol Double do
def double(input)
end
def double(int) do
int * 2
end
end
def double(list) do
list ++ list
end
end
4 = Double.double(2)
Documentation: Protocols
Map an enumerable
The map function enumerates an enumerable while applying a transform function and collects the
results into a list. Enum.map can be used to map a list, map a map, or map any enumerable.
# map a map
[:one, :two] = Enum.map(%{ one: 1, two: 2}, fn({k, v}) -> k end)
Documentation: Enum.map/2
With statement
The special form with is used to chain a sequence of matches in order and finally return the result of
do: if all the clauses match. However, if one of the clauses does not match, its result is immediately
returned.
do: parsed * 2
6 = with 2 <- 2,
1 <- 6,
do: 11
do: parsed * 2
Documentation: Kernel.SpecialForms.with/1
["ö"] = String.graphemes("ö")
["o", "̈
"] = String.codepoints("ö")
Documentation: String.graphemes/1
"AAA" = String.duplicate("A", 3)
"""
# on each line
"1\n2\n3\n" = """
"""
# Interpolated
~s"""
\"#{1}\"
\"#{2}\"
"""
# Not Interpolated
~S"""
"1"
"2"
"""
Documentation: String.downcase/1
"H" = String.at("Hello",0)
Documentation: String.at/2
Documentation: String.ends_with?/2
Documentation: String.upcase/1
stream = File.stream!("scratch.txt")
contents = File.read!("exists.txt")
# Raises a File.Error
contents = File.read!("doesnt_exist.txt")
In operator
The in operator tests for membership using === within an enumerable.
true = 1 in 1..4
true = File.exists?("exists.txt")
false = File.exists?("doesnt_exist.txt")
Word list
Word lists can be created using the ~w sigil.
is_atom(variable)
is_binary(variable)
is_bitstring(variable)
is_boolean(variable)
is_float(variable)
is_function(variable)
is_function(variable, arity)
is_integer(variable)
is_list(variable)
is_map(variable)
is_number(variable)
is_pid(variable)
is_port(variable)
is_reference(variable)
is_tuple(variable)
Return early
There is no return keyword so code must be organized to return early. The follow example shows how
to organize code to return early in Elixir.
def hello
if some_condition
return "Goodbye"
end
do_this()
do_something()
end
def hello do
if some_condition do
"Goodbye"
else
do_this()
do_something()
end
end
Case and cond can also be used to return different values based on a condition.
See Also:
Case Statement
Cond Statement
Truth table
The truth table for if/cond/unless statements in Elixir is simple: only nil and false evaluate to false. All
other values are true.
nil
false
Nil
This example shows example nil usage. Nil is frequently used as a return value to represent no value.
nil
true = is_nil(nil)
# nil is falsey
"ok"
end
1 = %{c: 1}.c
%{c: 1}.a
Range of characters
Character literals like ?a can be used to create a range of the ASCII integers of these characters. This
example could represent a range from a to z.
97..122 = ?a..?z
Range syntax
This example shows the literal syntax used to create a range.
1..4
4..1
Documentation: Range
Optional parameters
You can define a method with default arguments using the \\ syntax. The default arguments are used
when the argument is not provided.
"Hello #{name}"
end
defmodule User do
use Ecto.Schema
schema "users" do
end
def full_name(user) do
end
end
</tr>
</tr>
</tr>
Ruby Elixir
method/function "result"
"result"
end end
Variable #
# match operator
end end
Atoms #
# not garbage collected
:one :one
Division #
# use div/2 for integer division
5 / 2 == 2 5 / 2 == 2.5
If if true
if true do
end end
"No"
0 > 1 -> "No"
elsif 0 > 2
0 > 2 -> "Nope"
"Nope"
true -> "fallback"
else
end
"fallback"
#
end #
#
%{a: value} = %{a: 1}
#
# pattern matching can match against lite
#
# and be used in function definitions,
# end
Metaprogramming method_missing
# Macros
define_method
#
# et al #
Regex basics
Here are a few examples on how to use regular expressions in Elixir.
~r/foo/
~r/foo/ = ~r/#{"foo"}/
Documentation: Regex
Unless statement
Unless statement
"ok"
end
See Also: if
Filter list
Filter a list
Ternary
Ternary operator
Map to struct
Map to struct
defmodule User do
end
%{ b: value, d: value2 } = %{ a: 1, b: 2, d: 3 }
%{ a: value } = %{ a: 1, b: 2, d: 3 }
%{ c: value } = %{ a: 1, b: 2 }
Module definition
How to define a module in Elixir:
defmodule Example do
end
defmodule Example.Specific do
end
Documentation:
Modules Guide
Kernel.defmodule/2
Tuple syntax
This example shows the literal syntax to create a tuple and also how to pattern match.
{:ok, 1, "a"}
# pattern match
# empty tuple
{}
function definition
How to define a function/method in elixir:
defmodule Examples do
# basic defintion
"result"
end
#shorthand syntax
end
Anonymous functions
These examples show two syntaxes available to create anonymous functions.
square = fn(x) -> x * x end
4 = square.(2)
# to other functions
The shorthand syntax to create anonymous functions with the capture operator.
The syntax wraps an
expression with &() and each argument is indexed starting at 1 identified by &1 , &2 , and so on.
4 = square.(2)
four = &(2 + 2)
Cond statement
cond - similar to if, else if, else in other languages
end
Concatenate lists
List concatenation
Map syntax
Map syntax
# empty map
%{}
%{ one: 1, two: 2}
String concatenation
Concatenate strings
Documentation: Kernel.<>/2
Integer modulo
Modulo/Remainder of integer division
1 = rem(5, 2)
-1 = rem(-5, 2)
Documentation: Mix.Tasks.Ecto.Gen.Migration
See Also:
mix ecto.migrate
mix ecto.rollback
mix ecto.rollback
See Also:
mix ecto.migrate
mix ecto.gen.migration
mix ecto.migrate
See Also:
mix ecto.rollback
mix ecto.gen.migration
If statement
If statement
"good" = if true do
"good"
else
"This will"
end
nil = if false do
"good"
end
Documentation: Kernel.if/2
case statement
Case statement (similar to switch in other languages)
end
Documentation: Kernel.SpecialForms.case/2
Size of a tuple
Get the size/length of a tuple
3 = tuple_size({1, 2, 3})
Documentation: Kernel.tuple_size/1
Size of a map
Get the size/length of a map
1 = map_size(%{a: 1})
Documentation: Kernel.map_size/1
Length of list
Length of list
3 = length([1, 2, 3])
Documentation: Kernel.length/1
Documentation: Enum.into/2
Tuple to list
Tuple to list
Documentation: Tuple.to_list/1
Range to list
Range to list
Documentation: Enum.to_list/1
List comprehension
List comprehension
Print map
Prints a map
Print list
Prints a list
Print to console
Print to console
String interpolation
String interpolation
Atom to string
Convert an atom to a string
"hello" = Atom.to_string(:hello)
Documentation: Atom.to_string/1
Documentation: Enum.join/2
8.0 = :math.pow(2, 3)
Documentation: math.pow/2
Documentation: String.trim/1
Documentation: String.replace/4
Split a string
This example shows how to split a string on whitespace or split on a string.
Documentation:
String.split/3
String.split/1
Prepend to list
Prepend to list
Documentation: Integer.parse/2
Integer division
Integer division
2 = div(11, 4)
Head of a list
Get the head of a list
1 = hd([1, 2, 3, 4])
# head contains 1
%{ %{} | new_key: 1}
Reverse a string
Reverse a string
"olleh" = String.reverse("hello")
language examples.
RSS
elixir-examples
elixirexamples