2. CPUs en los últimas décadas
Ref: https://github.com/karlrupp/microprocessor-trend-data/tree/master/42yrs
3. Functional programming
En ciencias de la computación, la programación funcional es un
paradigma de programación declarativa basado en el uso de
funciones matemáticas, en contraste con la programación
imperativa, que enfatiza los cambios de estado mediante la
mutación de variables.
https://es.wikipedia.org/wiki/Programación_funcional
4. Functional programming 2
El bloque básico son las funciones, los valores
no cambian y el código es (principalmente) declarativo.
OOP: Objetos manipulados a través de métodos
FP: Estructuras de datos manipulados a través de funciones
5. JavaScript vs Elixir
var list = ["dogs", "hot dogs", "bananas"];
function upcase(list) {
var newList = [];
for (var i = 0; i < list.length; i++) {
newList.push(list[i].toUpperCase());
}
return newList; }
upcase(list);
// => ["DOGS", "HOT DOGS", "BANANAS"]
defmodule StringList do
def upcase([]), do: []
def upcase([first | rest]), do: [String.upcase(first) | upcase(rest)]
end
StringList.upcase(["dogs", "hot dogs", "bananas"])
# => ["DOGS", "HOT DOGS", "BANANAS"]
15. pattern matching
iex(68)> x = 42
42
iex(69)> 42 = x
42
iex(70)> 1 = x
** (MatchError) no match of right hand side value: 42
iex(72)> {a, b, c} = {:hello, "Ermua", 55}
{:hello, "Ermua", 55}
iex(73)> a
:hello
iex(74)> b
"Ermua"
iex(76)> {a, b, c} = {:hello, "Ermua"}
** (MatchError) no match of right hand side value: {:hello, "Ermua"}
iex(94)> [a, b, c] = [5, 6, 7]
[5, 6, 7]
iex(95)> b
6
iex(96)> [h | t] = [3, 4, 5, 6]
[3, 4, 5, 6]
iex(97)> h
3
iex(98)> t
[4, 5, 6]
16. case
case {1, 2, 3} do
{4, 5, 6} ->
"Esto no pasa nunca, no hay match"
{1, x, 3} ->
"Aquí el x tendrá valor 3"
_ ->
"Esto esta match-edado siempre"
end
17. modules and functions
defmodule Math do
def sum(a, b) do
do_sum(a, b)
end
defp do_sum(a, b) do
a + b
end
end
IO.puts Math.sum(1, 2) #=> 3
IO.puts Math.do_sum(1, 2) #=> ** (UndefinedFunctionError)
18. Pattern matching en argumentos
defmodule Talker do
def say_hello("Bob"), do: "Hello, Bob!"
def say_hello("Jon"), do: "Hi there, Jon!"
def say_hello(name) do
"Hi, #{name}."
end
end
defmodule Talker do
def say_hello(nil), do: "Please give me a name"
def say_hello(name) do
"Hi, #{name}."
end
end
19. recursion por todas partes
defmodule Math do
def double_each([head | tail]) do
[head * 2 | double_each(tail)]
end
def double_each([]) do
[]
end
end
iex> Math.double_each([1, 2, 3]) #=> [2, 4, 6]
defmodule Math do
def sum_list([head | tail], accumulator) do
sum_list(tail, head + accumulator)
end
def sum_list([], accumulator) do
accumulator
end
end
iex> Math.sum_list([1, 2, 3], 0) #=> 6
20. Máquina virtual de Erlang (BEAM) y procesos
iex(111)> pid = spawn fn -> 42*2 end
#PID<0.220.0>
iex(112)> Process.alive?(pid)
false
iex(116)> self()
#PID<0.101.0>
iex(117)> Process.alive?(self())
true
iex(120)> self |> Process.alive?
true
Ref: img de https://speakerdeck.com/sasajuric
22. Monte Carlo y pi
defmodule MonteCarlo do
def pi(n) do
count = Enum.count(1..n, fn _ ->
x = :rand.uniform
y = :rand.uniform
:math.sqrt(x*x + y*y) <= 1
end)
pi = 4 * count / n
IO.puts "Iteraciones: #{n}, valor de pi: #{pi}"
end
end
iex(59)> spawn fn -> MonteCarlo.pi(10_000) end
#PID<0.6145.0>
Iterations: 10000, pi value: 3.158
Nota: lanzar múltiples procesos y observar htop y :observer
34. Phoenix: proyecto nuevo
$ mix phx.new hello_phoenix
* creating hello_phoenix/config/config.exs
* creating hello_phoenix/config/dev.exs
* creating hello_phoenix/config/prod.exs]
* ...
* We are almost there! The following steps are missing:
* $ cd hello_phoenix
* Then configure your database in config/dev.exs and run:
* $ mix ecto.create
* Start your Phoenix app with:
* $ mix phx.server
* You can also run your app inside IEx (Interactive Elixir) as:
* $ iex -S mix phx.server
35. Phoenix: iniciar
$ mix ecto.create
Compiling 13 files (.ex)
Generated hello_phoenix app
The database for HelloPhoenix.Repo has been created
$ mix phx.server
[info] Running HelloPhoenixWeb.Endpoint with cowboy 2.6.1 at http://
localhost:4000
36. Phoenix: live reload, channels
$ vi ./lib/hello_phoenix_web/templates/page/index.html.eex