cheatsheets/elixir.md

763 lines
11 KiB
Markdown
Raw Permalink Normal View History

2016-01-07 05:47:48 +01:00
---
title: Elixir
2017-08-28 19:25:55 +02:00
category: Elixir
2017-08-28 21:18:32 +02:00
tags: [New]
2020-07-04 15:33:09 +02:00
updated: 2018-07-04
2017-08-29 18:57:42 +02:00
weight: -10
2016-01-07 05:47:48 +01:00
---
2017-08-29 19:24:56 +02:00
## Getting started
{: .-three-column}
### Hello world
{: .-prime}
```elixir
# hello.exs
defmodule Greeter do
def greet(name) do
2017-09-15 13:12:14 +02:00
message = "Hello, " <> name <> "!"
IO.puts message
2017-08-29 19:24:56 +02:00
end
end
Greeter.greet("world")
```
```bash
elixir hello.exs
# Hello, world!
```
{: .-setup}
### Variables
```elixir
age = 23
```
### Maps
```elixir
user = %{
name: "John",
city: "Melbourne"
}
```
```elixir
IO.puts "Hello, " <> user.name
```
{: .-setup}
### Lists
```elixir
users = [ "Tom", "Dick", "Harry" ]
```
{: data-line="1"}
```elixir
Enum.map(users, fn user ->
2017-08-29 19:24:56 +02:00
IO.puts "Hello " <> user
end)
```
### Piping
```elixir
source
|> transform(:hello)
|> print()
```
{: data-line="2,3"}
```elixir
# Same as:
print(transform(source, :hello))
```
These two are equivalent.
### Pattern matching
```elixir
user = %{name: "Tom", age: 23}
%{name: username} = user
```
{: data-line="2"}
This sets `username` to `"Tom"`.
### Pattern matching in functions
```elixir
def greet(%{name: username}) do
IO.puts "Hello, " <> username
end
user = %{name: "Tom", age: 23}
```
{: data-line="1"}
Pattern matching works in function parameters too.
2017-08-29 19:29:08 +02:00
Control flow
------------
{: .-three-column}
### If
```elixir
if false do
"This will never be seen"
else
"This will"
end
```
### Case
```elixir
case {1, 2, 3} do
{4, 5, 6} ->
"This clause won't match"
{1, x, 3} ->
2018-03-17 06:25:56 +01:00
"This will match and bind x to 2"
_ ->
2018-03-17 06:25:56 +01:00
"This will match any value"
end
```
2017-08-29 19:29:08 +02:00
### Cond
```elixir
cond do
1 + 1 == 3 ->
"I will never be seen"
2 * 5 == 12 ->
"Me neither"
true ->
2017-08-29 19:29:08 +02:00
"But I will (this is essentially an else)"
end
```
2021-12-13 00:25:41 +01:00
### With
```elixir
with {:ok, {int, _asdf}} <- Integer.parse("123asdf"),
{:ok, datetime, _utc_offset} <- DateTime.from_iso8601("2021-10-27T12:00:00Z") do
DateTime.add(datetime, int, :second)
# optional else clause. if not provided and an error occurs, the error is returned
else
:error -> "couldn't parse integer string"
{:error, :invalid_format} -> "couldn't parse date string"
_ -> "this will never get hit because all errors are handled"
end
```
2017-08-29 19:29:08 +02:00
### Errors
```elixir
try do
throw(:hello)
catch
message -> "Got #{message}."
after
IO.puts("I'm the after clause.")
end
```
2017-08-29 19:24:56 +02:00
## Types
2016-06-03 00:36:03 +02:00
2017-08-24 17:27:32 +02:00
### Primitives
2016-06-03 00:36:03 +02:00
2017-08-29 19:34:51 +02:00
| Sample | Type |
| --- | --- |
| `nil` | Nil/null |
| `true` _/_ `false` | Boolean |
| --- | --- |
| `?a` | Integer (ASCII) |
| `23` | Integer |
| `3.14` | Float |
| --- | --- |
| `'hello'` | Charlist |
2017-08-29 19:34:51 +02:00
| `<<2, 3>>` | Binary |
| `"hello"` | Binary string |
| `:hello` | Atom |
| --- | --- |
| `[a, b]` | List |
| `{a, b}` | Tuple |
| --- | --- |
| `%{a: "hello"}` | Map |
| `%MyStruct{a: "hello"}` | Struct |
| `fn -> ... end` | Function |
2016-06-03 00:36:03 +02:00
2017-08-24 17:27:32 +02:00
### Type checks
2016-01-07 05:47:48 +01:00
```elixir
is_atom/1
is_bitstring/1
is_boolean/1
is_function/1
is_function/2
is_integer/1
is_float/1
2017-08-24 17:27:32 +02:00
```
2016-01-07 05:47:48 +01:00
2017-08-24 17:27:32 +02:00
```elixir
2016-01-07 05:47:48 +01:00
is_binary/1
is_list/1
is_map/1
is_tuple/1
2017-08-24 17:27:32 +02:00
```
2016-01-07 05:47:48 +01:00
2017-08-24 17:27:32 +02:00
```elixir
2016-01-07 05:47:48 +01:00
is_nil/1
is_number/1
is_pid/1
is_port/1
is_reference/1
```
### Operators
```elixir
left != right # equal
left !== right # match
left ++ right # concat lists
2016-06-02 11:39:31 +02:00
left <> right # concat string/binary
2016-01-07 05:47:48 +01:00
left =~ right # regexp
```
2017-08-29 19:32:59 +02:00
Modules
-------
2017-08-24 17:27:32 +02:00
### Importing
2016-01-07 05:47:48 +01:00
```elixir
2017-08-24 17:27:32 +02:00
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
```elixir
alias Foo.Bar, as: Bar
alias Foo.Bar # same as above
alias Foo.{Bar, Baz}
2016-01-07 05:47:48 +01:00
```
2016-06-03 00:36:03 +02:00
## String
2016-01-07 05:47:48 +01:00
2017-08-24 17:27:32 +02:00
### Functions
2016-01-07 05:47:48 +01:00
```elixir
2016-06-02 11:39:31 +02:00
import String
2017-08-24 17:27:32 +02:00
```
2017-08-31 19:39:38 +02:00
{: .-setup}
2017-08-24 17:27:32 +02:00
```elixir
2016-06-02 11:39:31 +02:00
str = "hello"
2017-08-31 19:39:38 +02:00
str |> length() # → 5
str |> codepoints() # → ["h", "e", "l", "l", "o"]
str |> slice(2..-1) # → "llo"
str |> split(" ") # → ["hello"]
str |> capitalize() # → "Hello"
2016-06-02 11:39:31 +02:00
str |> match(regex)
```
2017-08-24 17:27:32 +02:00
### Inspecting objects
```elixir
inspect(object, opts \\ [])
```
```elixir
value |> IO.inspect()
```
2018-06-29 02:03:23 +02:00
```elixir
value |> IO.inspect(label: "value")
```
2017-08-24 17:27:32 +02:00
2016-06-03 01:01:18 +02:00
## Numbers
2017-08-24 17:27:32 +02:00
### Operations
2016-06-03 01:01:18 +02:00
```elixir
abs(n)
2017-08-24 17:27:32 +02:00
round(n)
2016-06-03 01:01:18 +02:00
rem(a, b) # remainder (modulo)
div(a, b) # integer division
```
2016-06-02 11:39:31 +02:00
### Float
```elixir
import Float
2017-08-24 17:27:32 +02:00
```
2017-08-31 19:39:38 +02:00
{: .-setup}
2017-08-24 17:27:32 +02:00
```elixir
2016-06-02 11:39:31 +02:00
n = 10.3
2017-08-31 19:39:38 +02:00
```
{: .-setup}
```elixir
n |> ceil() # → 11.0
n |> ceil(2) # → 11.30
n |> to_string() # → "1.030000+e01"
2016-06-02 11:39:31 +02:00
n |> to_string([decimals: 2, compact: true])
2017-08-31 19:39:38 +02:00
```
2016-06-02 11:39:31 +02:00
2017-08-31 19:39:38 +02:00
```elixir
Float.parse("34") # → { 34.0, "" }
2016-06-02 11:39:31 +02:00
```
### Integer
```elixir
import Integer
2017-08-24 17:27:32 +02:00
```
2017-08-31 19:39:38 +02:00
{: .-setup}
2017-08-24 17:27:32 +02:00
```elixir
2016-06-02 11:39:31 +02:00
n = 12
2017-08-31 19:39:38 +02:00
```
{: .-setup}
```elixir
n |> digits() # → [1, 2]
n |> to_charlist() # → '12'
2017-08-31 19:39:38 +02:00
n |> to_string() # → "12"
2017-08-24 17:27:32 +02:00
n |> is_even()
n |> is_odd()
2017-08-31 19:39:38 +02:00
```
2016-06-02 11:39:31 +02:00
2017-08-31 19:39:38 +02:00
```elixir
2016-06-02 11:39:31 +02:00
# Different base:
2017-08-31 19:39:38 +02:00
n |> digits(2) # → [1, 1, 0, 0]
n |> to_charlist(2) # → '1100'
2017-08-31 19:39:38 +02:00
n |> to_string(2) # → "1100"
```
2016-06-02 11:39:31 +02:00
2017-08-31 19:39:38 +02:00
```elixir
parse("12") # → {12, ""}
undigits([1, 2]) # → 12
2016-06-02 11:39:31 +02:00
```
### Type casting
```elixir
2017-08-31 19:39:38 +02:00
Float.parse("34.1") # → {34.1, ""}
Integer.parse("34") # → {34, ""}
```
2016-06-02 11:39:31 +02:00
2017-08-31 19:39:38 +02:00
```elixir
Float.to_string(34.1) # → "3.4100e+01"
Float.to_string(34.1, [decimals: 2, compact: true]) # → "34.1"
2016-06-02 11:39:31 +02:00
```
2016-06-03 01:01:18 +02:00
## Map
2016-06-02 11:39:31 +02:00
2017-08-24 17:27:32 +02:00
### Defining
2016-06-03 01:01:18 +02:00
```elixir
2017-08-31 19:39:38 +02:00
m = %{name: "hi"} # atom keys (:name)
m = %{"name" => "hi"} # string keys ("name")
2016-06-03 01:01:18 +02:00
```
### Updating
2017-08-24 17:27:32 +02:00
2016-06-03 01:01:18 +02:00
```elixir
2016-06-02 11:39:31 +02:00
import Map
2017-08-31 19:39:38 +02:00
```
{: .-setup}
2016-06-02 11:39:31 +02:00
2017-08-31 19:39:38 +02:00
```elixir
m = %{m | name: "yo"} # key must exist
```
2016-06-03 01:01:18 +02:00
2017-08-31 19:39:38 +02:00
```elixir
m |> put(:id, 2) # → %{id: 2, name: "hi"}
m |> put_new(:id, 2) # only if `id` doesn't exist (`||=`)
```
2016-06-03 01:01:18 +02:00
2017-08-31 19:39:38 +02:00
```elixir
m |> put(:b, "Banana")
m |> merge(%{b: "Banana"})
m |> update(:a, &(&1 + 1))
m |> update(:a, fun a -> a + 1 end)
```
2016-06-03 01:01:18 +02:00
2017-08-31 19:39:38 +02:00
```elixir
m |> get_and_update(:a, &(&1 || "default"))
# → {old, new}
2016-06-03 01:01:18 +02:00
```
### Deleting
2017-08-24 17:27:32 +02:00
2016-06-03 01:01:18 +02:00
```elixir
2017-08-31 19:39:38 +02:00
m |> delete(:name) # → %{}
m |> pop(:name) # → {"John", %{}}
2016-06-03 01:01:18 +02:00
```
2016-06-02 11:39:31 +02:00
2016-06-03 01:01:18 +02:00
### Reading
2016-06-02 11:39:31 +02:00
2016-06-03 01:01:18 +02:00
```elixir
2017-08-31 19:39:38 +02:00
m |> get(:id) # → 1
m |> keys() # → [:id, :name]
m |> values() # → [1, "hi"]
```
2016-06-02 11:39:31 +02:00
2017-08-31 19:39:38 +02:00
```elixir
m |> to_list() # → [id: 1, name: "hi"]
# → [{:id, 1}, {:name, "hi"}]
2016-06-03 01:01:18 +02:00
```
### Deep
```elixir
put_in(map, [:b, :c], "Banana")
put_in(map[:b][:c], "Banana") # via macros
2017-08-31 19:39:38 +02:00
```
```elixir
2016-06-03 01:01:18 +02:00
get_and_update_in(users, ["john", :age], &{&1, &1 + 1})
```
2016-06-02 11:39:31 +02:00
2017-08-31 19:39:38 +02:00
### Constructing from lists
2016-06-02 11:39:31 +02:00
2016-06-03 01:01:18 +02:00
```elixir
2016-06-02 11:39:31 +02:00
Map.new([{:b, 1}, {:a, 2}])
Map.new([a: 1, b: 2])
2017-08-31 19:39:38 +02:00
Map.new([:a, :b], fn x -> {x, x} end) # → %{a: :a, b: :b}
2016-06-02 11:39:31 +02:00
```
### Working with structs
#### Struct to map
```elixir
Map.from_struct(%AnyStruct{a: "b"}) # → %{a: "b"}
```
#### Map to struct
```elixir
struct(AnyStruct, %{a: "b"}) # → %AnyStruct{a: "b"}
```
2016-06-03 01:01:18 +02:00
## List
2016-06-02 11:39:31 +02:00
2017-08-31 19:39:38 +02:00
```elixir
2016-06-02 11:39:31 +02:00
import List
2017-08-31 19:39:38 +02:00
```
{: .-setup}
2016-06-02 11:39:31 +02:00
2017-08-31 19:39:38 +02:00
```elixir
l = [ 1, 2, 3, 4 ]
```
{: .-setup}
2016-06-02 11:39:31 +02:00
2017-08-31 19:39:38 +02:00
```elixir
l = l ++ [5] # push (append)
l = [ 0 | list ] # unshift (prepend)
```
```elixir
l |> first()
l |> last()
```
```elixir
l |> flatten()
l |> flatten(tail)
2016-01-07 05:47:48 +01:00
```
2017-08-24 17:27:32 +02:00
Also see [Enum](#enum).
2016-06-03 01:01:18 +02:00
## Enum
2016-01-07 05:47:48 +01:00
2017-08-31 19:39:38 +02:00
### Usage
2016-01-07 05:47:48 +01:00
```elixir
2016-06-02 11:39:31 +02:00
import Enum
2017-08-31 19:39:38 +02:00
```
{: .-setup}
2016-06-02 11:39:31 +02:00
2017-08-31 19:39:38 +02:00
```elixir
2016-06-02 11:39:31 +02:00
list = [:a, :b, :c]
2017-08-31 19:39:38 +02:00
```
{: .-setup}
2016-06-02 11:39:31 +02:00
2017-08-31 19:39:38 +02:00
```elixir
list |> at(0) # → :a
list |> count() # → 3
list |> empty?() # → false
list |> any?() # → true
```
```elixir
2018-01-04 02:12:25 +01:00
list |> concat([:d]) # → [:a, :b, :c, :d]
2016-01-07 05:47:48 +01:00
```
2017-08-24 17:27:32 +02:00
Also, consider streams instead.
2017-08-31 19:39:38 +02:00
### Map/reduce
```elixir
list |> reduce(fn)
list |> reduce(acc, fn)
list |> map(fn)
list |> reject(fn)
list |> any?(fn)
list |> empty?(fn)
```
```elixir
[1, 2, 3, 4]
|> Enum.reduce(0, fn(x, acc) -> x + acc end)
```
## Tuple
2016-06-03 01:01:18 +02:00
2017-08-24 17:27:32 +02:00
### Tuples
2016-06-03 01:01:18 +02:00
```elixir
2017-08-31 19:39:38 +02:00
import Tuple
```
{: .-setup}
2016-06-03 01:01:18 +02:00
2017-08-31 19:39:38 +02:00
```elixir
t = { :a, :b }
```
```elixir
t |> elem(1) # like tuple[1]
t |> put_elem(index, value)
t |> tuple_size()
2016-06-03 01:01:18 +02:00
```
### Keyword lists
```elixir
list = [{ :name, "John" }, { :age, 15 }]
2016-06-09 23:19:00 +02:00
list[:name]
2017-08-31 19:39:38 +02:00
```
2016-06-09 23:19:00 +02:00
2017-08-31 19:39:38 +02:00
```elixir
# For string-keyed keyword lists
2016-06-09 23:19:00 +02:00
list = [{"size", 2}, {"type", "shoe"}]
2017-08-31 19:39:38 +02:00
List.keyfind(list, "size", 0) # → {"size", 2}
2016-06-03 01:01:18 +02:00
```
## Functions
### Lambdas
```elixir
square = fn n -> n*n end
square.(20)
```
### & syntax
```elixir
square = &(&1 * &1)
square.(20)
square = &Math.square/1
```
### Running
```elixir
fun.(args)
apply(fun, args)
apply(module, fun, args)
```
2016-06-02 11:39:31 +02:00
2017-08-24 17:27:32 +02:00
### Function heads
2016-06-02 11:39:31 +02:00
2017-08-24 17:27:32 +02:00
```elixir
def join(a, b \\ nil)
def join(a, b) when is_nil(b) do: a
def join(a, b) do: a <> b
```
## Structs
### Structs
2016-06-02 11:39:31 +02:00
```elixir
defmodule User do
defstruct name: "", age: nil
end
%User{name: "John", age: 20}
2016-06-03 00:36:03 +02:00
2017-08-31 19:39:38 +02:00
%User{}.struct # → User
2016-06-02 11:39:31 +02:00
```
2017-08-24 17:27:32 +02:00
See: [Structs](http://elixir-lang.org/getting-started/structs.html)
2016-06-02 22:41:26 +02:00
2016-06-03 00:36:03 +02:00
## Protocols
2017-08-24 17:27:32 +02:00
### Defining protocols
2016-06-03 00:36:03 +02:00
```elixir
defprotocol Blank do
@doc "Returns true if data is considered blank/empty"
def blank?(data)
end
```
```elixir
defimpl Blank, for: List do
def blank?([]), do: true
def blank?(_), do: false
end
2017-08-31 19:39:38 +02:00
Blank.blank?([]) # → true
2016-06-03 00:36:03 +02:00
```
### Any
```elixir
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
2017-08-24 17:27:32 +02:00
### For
2016-06-03 00:36:03 +02:00
```elixir
for n <- [1, 2, 3, 4], do: n * n
for n <- 1..4, do: n * n
2017-08-31 19:39:38 +02:00
```
2016-06-03 00:36:03 +02:00
2017-08-31 19:39:38 +02:00
```elixir
for {key, val} <- %{a: 10, b: 20}, do: val
# → [10, 20]
```
```elixir
2016-06-03 00:36:03 +02:00
for {key, val} <- %{a: 10, b: 20}, into: %{}, do: {key, val*val}
```
### Conditions
```elixir
for n <- 1..10, rem(n, 2) == 0, do: n
2017-08-31 19:39:38 +02:00
# → [2, 4, 6, 8, 10]
2016-06-03 00:36:03 +02:00
```
### Complex
```elixir
for dir <- dirs,
file <- File.ls!(dir), # nested comprehension
path = Path.join(dir, file), # invoked
File.regular?(path) do # condition
2016-06-03 01:01:18 +02:00
IO.puts(file)
2016-06-03 00:36:03 +02:00
end
```
2017-08-24 17:27:32 +02:00
## Misc
2016-06-02 22:41:26 +02:00
### Metaprogramming
```elixir
__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
```
2017-08-24 17:27:32 +02:00
### Regexp
2016-06-03 00:36:03 +02:00
```elixir
exp = ~r/hello/
exp = ~r/hello/i
"hello world" =~ exp
```
2017-08-24 17:27:32 +02:00
### Sigils
2016-06-03 00:36:03 +02:00
```elixir
~r/regexp/
~w(list of strings)
~s|strings with #{interpolation} and \x20 escape codes|
~S|no interpolation and no escapes|
~c(charlist)
2016-06-03 00:36:03 +02:00
```
2017-08-24 17:27:32 +02:00
Allowed chars: `/` `|` `"` `'` `(` `[` `{` `<` `"""`.
See: [Sigils](http://elixir-lang.org/getting-started/sigils.html)
2016-06-03 00:36:03 +02:00
2017-08-24 17:27:32 +02:00
### Type specs
2016-06-03 00:36:03 +02:00
```elixir
@spec round(number) :: integer
@type number_with_remark :: {number, String.t}
@spec add(number, number) :: number_with_remark
```
2017-08-24 17:27:32 +02:00
Useful for [dialyzer](http://www.erlang.org/doc/man/dialyzer.html).
See: [Typespecs](http://elixir-lang.org/getting-started/typespecs-and-behaviours.html)
### Behaviours
2016-06-03 00:36:03 +02:00
```elixir
defmodule Parser do
@callback parse(String.t) :: any
@callback extensions() :: [String.t]
end
```
```elixir
defmodule JSONParser do
@behaviour Parser
def parse(str), do: # ... parse JSON
def extensions, do: ["json"]
end
```
2017-08-24 17:27:32 +02:00
See: [Module](http://elixir-lang.org/docs/stable/elixir/Module.html)
2016-06-03 01:01:18 +02:00
## References
2017-08-24 17:27:32 +02:00
{: .-one-column}
2016-06-03 01:01:18 +02:00
- [Learn Elixir in Y minutes](https://learnxinyminutes.com/docs/elixir/)