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
}