elixir KERNEL 4 Flashcards
defmodule Sum do
def add(pid, x, y) do
send(pid, x + y)
end
end
spawn(Sum, :add, [self(), 1, 2])
receive do val -> val end
=> 3
pets = %{
“cat” => %{age: 1},
“dog” => %{age: 3}
}
pets[“cat”][:age] |> update_in(&(&1 + 1))
=> %{
“cat” => %{age: 2},
“dog” => %{age: 3}
}
c = %{age: 5}
v = %{age: 20}
auto = %{“car” => c, “van” => v}
add1 = &(&1 + 1)
auto[“van”].age |> update_in(add1)
%{“car” => %{age:5}, “van” => %{age: 21}}
e = %{age: 4}
m = %{age: 7}
dogs = %{ellie: e, max: m}
update_in(dogs.max.age, &(&1 + 1))
%{ellie: %{age:4}, max: %{age: 8}}
b = %{age: 1}
c = %{age: 2}
toys = %{“bear” => b, “car” => c}
plus1 = &(&1 + 1)
toys |> update_in([“car”, :age], plus1)
%{“bear” => %{age: 1}, %{“car” => %{age: 3}}
defmodule Add do
def inc(pid, x),
do: send(pid, x + 1)
end
spawn_link(Add, :inc, [self(), 1])
receive do
val -> val
end
=> 2
b = %{age: 1}
a = %{age: 2}
bots = %{“bob” => b, “amy” => a}
bots[“bob”][:age] |> get_and_update_in(&{&1, &1+1})
=> %{“bob” => %{age: 2}, “amy” => %{age: 2}}
abs(-1.11)
=> 1.11
abs(28)
=> 28
ceil(-1.25)
=> -1
floor(3.55)
=> 3
1 in {1, 2, 3}
** (Protocol.UndefinedError)
protocol Enumerable not implemented for {1, 2, 3}
*Note: Tuple is a basic type,
but in/2 expects an enumerable on the right side
1 in [1, 2] == Enum.member?([1, 2], 1)
=> true
x = 1
case x do
x when x in [2, 3] -> “boo”
x when x in 0..2 -> “foo”
_x => “whatevs”
end
=> “foo”
c = %{age: 30}
n = %{age:20}
jobs = %{“cop” => c, “nun” => n}
jobs[“cop”].age |> get_and_update_in(&(&1, &1+1))
=> {30, “cop” => %{age: 31}, “nun” => %{age: 20}}
is_map_key(%{a: 1}, :a)
=> true
1 not in [1, 2, 3]
=> false
defmodule Feeling do
def love, do: “love you!”
end
Feeling.love()
=> “love you!”
is_map_key(:a, %{a: 1})
BadMapError
*Note: is_map_key/2 expects a map as a first argument
pets = %{amy: %{age: 7}, mia: %{age: 8}}
pets.amy.age |> get_and_update_in(&(&1, &1 + 1))
=> {7, %{amy: %{age: 8}, mia: %{age: 8}}}
is_struct(URI.parse(“/”))
=> true
eg: URI.parse(“https://hexdocs.pm/elixir/Kernel.html#content”) =>
%URI{
authority: “hexdocs.pm”,
fragment: “content”,
host: “hexdocs.pm”,
path: “/elixir/Kernel.html”,
port: 443,
query: nil,
scheme: “https”,
userinfo: nil
}
is_struct(%{})
=> false
defmodule Lang do
def desc(a, b) do
”#{a} #{b}”
end
end
Lang.desc(“elixir”, “cool”)
=> “elixir cool”
throw “hello”
** (throw) “hello”
defmodule Inc do
def add(x, inc_by \1) do
x + inc_by
end
end
Inc.add(1)
=> 2
*Note: Inc.add(3, 5) => 8
defmodule Title do
def name(name, title \ “”)
def name(name, title) do
title <> name
end
end
Title.name(“Smith”, “Dr.”
=> “Dr.Smith”
*Note: if only 1 argument is provided, the first def is called and name and default title are fed into the second def because there is no instruction block defined by the first def.
Therefore, Title.name(“Johnson”) => “Johnson”
all = fn :get_and_update, data, next -> Enum.map(data, next) end
get_and_update_in(
[%{x: 1, y: 0}, %{x: 0, y: 0}],
[all, :x],
&{&1, &1 +1}
)
=> [
{1, %{x: 2, y: 0}},
{0, %{x: 1, y: 0}}
]
try do
throw(:catch_this)
catch
:throw, :catch_this -> :it_was_caught
end
=> :it_was_caught
defmodule Title do
def name(name, title \ “”)
def name(name, title) do
title <> name
end
end
Title.name(“Smith”)
=> “Smith”
try do
throw(:tantrum)
catch
:throw, value -> value
after
IO.puts “Are you ok?”
end
=> :tantrum
*Note: “Are you ok?” would be printed
before returning the value of throw.
defmodule End do
def perform(reason) do
exit reason
catch
:exit, _ -> “Or keep going?”
end
end
End.perform(“Give up”)
=> “Or keep going?”
try do
throw(:ball)
catch
x -> x
end
:ball
try do
throw(:tantrum)
catch
_value -> __STACKTRACE__
end
Returns a stacktrace
Example from my particular iex session:
[
{:erl_eval, :do_apply, 6, [file: ‘erl_eval.erl’, line: 680]},
{:erl_eval, :try_clauses, 8, [file: ‘erl_eval.erl’, line: 914]},
{:elixir, :recur_eval, 3, [file: ‘src/elixir.erl’, line: 278]},
{:elixir, :eval_forms, 3, [file: ‘src/elixir.erl’, line: 263]},
{IEx.Evaluator, :handle_eval, 5, [file: ‘lib/iex/evaluator.ex’, line: 258]},
{IEx.Evaluator, :do_eval, 3, [file: ‘lib/iex/evaluator.ex’, line: 239]},
{IEx.Evaluator, :eval, 3, [file: ‘lib/iex/evaluator.ex’, line: 217]},
{IEx.Evaluator, :loop, 1, [file: ‘lib/iex/evaluator.ex’, line: 103]}
]
destructure([x, y], [1, 2, 3])
{x, y}
=> {1, 2}
destructure([a, b], [“oy”])
“a is #{a} and b is #{b}”
=> “a is oy and b is “
score = %{rob: %{win: 2}, ann: %{win: 3}}
get_and_update_in(score, [:rob, :win], &{&1, &1 + 1})
{2, %{ann: %{win: 3}, rob %{win: 3}}
defstructure([x, y], [1])
{x, y}
=> {1, nil}
a = “a”
destructure([^a, 1], [:a, 1])
** (MatchError) no match of right hand side value: [:a, 1]
defmodule Car do
defstruct color: :red
end
struct(Car)
=> %Car{color: :red}
defmodule Car do
defstruct color: :red
end
struct(Car, color: :blue)
=> %Car{color: :blue}
defmodule Pet do
defstruct name: “Bob”
end
pet = struct(Pet, name: “Mia”)
struct(pet, age: 1)
=> %Pet{name: “Mia”}
defmodule Lang do
defstruct name: “Eli” <> “xir”
end
struct(Lang, %{“name” => “ruby”})
=> %Lang{name: “Elixir”}
defmodule Car do
defstruct make: :BMW
end
a = struct(Car)
b = %{make: :BMW, __struct__: Car}
a == b
=> true
defmodule Car do
defstruct [:make]
end
struct(Car)
=> %Car{make: nil}
defmodule Car do
@enforce_keys [:make]
defstruct [:make]
end
struct(Car)
=> %Car{make: nil}
*Note:
enforce_keys has no effect here.
Use struct!/2 or % to enforce keys
defmodule Car do
@enforce_keys [:make]
defstruct [:make]
end
struct!(Car)
** (ArgumentError)
The following keys must also be given when building struct Car:
[:make]
defmodule Car do
defstruct [:make]
end
struct!(Car)
=> %Car{make: nil}
defmodule Car do
defstruct [:make]
end
struct!(Car, color: :red)
** (KeyError) key :color not found in: %Car{make: nil}
defmodule Child do
defstruct name: “El”
end
a = struct!(%Child{})
struct!(a, age: 1)
** (KeyError) key :age not found in: %Child{name: “El”}
~U[2020-03-01T20:00:07.001+00:00]
~U[2020-03-01 20:00:07.001Z]
Define a type, t, for given module so its type can be referenced as User.t
defmodule User do
defstruct name: “Bob”, age: 18
end
@type t :: %__MODULE__{
name: String.t(),
age: non_neg_integer
}
~U[2020-03-01 20:34:00Z]
=> ~U[2020-03-01 20:34:00Z]
:a in [:”a”]
=> true
pid = self()
fn -> send(pid, 1 + 1) end
|> spawn_link()
receive do
val -> val
end
=> 2