12
Elixir Abdulsattar - http://bimorphic.com

Introducing Elixir

Embed Size (px)

Citation preview

Page 1: Introducing Elixir

ElixirAbdulsattar - http://bimorphic.com

Page 2: Introducing Elixir

FeaturesDynamicFunctionalPattern MatchingRuby inspired syntaxExtensible: macrosConcurrency, Distributed and Fault tolerant

Page 3: Introducing Elixir

Data Types/Structures1 # integer2.0 # floattrue # boolean:atom # atom / symbol'elixir' # character list"elixir" # string[1, 2, 3] # list{1,2} # tuple[{:a, 1}, {:b, 2}] # keyword list[a: 1, b: 2] # ^ same keyword list%{a: 1, b: 2, c: 3} # hash

Page 4: Introducing Elixir

Pattern Matchinga = 1{x, y} = {0, 0}[head | tail] = [1, 2, 3]

result = case {1, 2, 3} do {4, 5, 6} -> "Doesn't match" {1, x, 3} when x > 3 -> "doesn't match because 2 < 3" {x, 2, 3} -> "matches and x is #{x}" _ -> "matches if nothing above matches"end

def zero?(0), do: truedef zero?(x) when is_number(x), do: false

Page 5: Introducing Elixir

Modulesdefmodule Math do def sum(a, b) do a + b end

def sub(a, b) do a - b endend

IO.puts (Math.sum(3,4))

Page 6: Introducing Elixir

Structsdefmodule Person do defstruct name: "Sattar", age: 40end

me = %Person{name: "AbdulSattar"}IO.puts me.name # Abdulsattar

%Person{name: name, age: age} = meIO.puts(age) # 40

youngMe = %{me | age: 10}

Page 7: Introducing Elixir

Protocolsdefprotocol Blank do @doc "Returns true if data is considered blank/empty" def blank?(data)end

defimpl Blank, for: Integer do def blank?(0), do: true def blank?(_), do: falseend

defimpl Blank, for: List do def blank?([]), do: true def blank?(_), do: falseend

Blank.blank?(3) # falseBlank.blank?([]) # true

Page 8: Introducing Elixir

Enumerablesiex(2)> Enum.map([1, 2, 3], fn x -> x * x end)[1, 4, 9]iex(3)> Enum.map([1, 2, 3], &(&1 * &1))[1, 4, 9]iex(4)> Enum.reduce(1..100, 0, &+/2)5050

Page 9: Introducing Elixir

Pipe OperatorsumOfSquares = Enum.reduce(Enum.map(1..100, fn x -> x * x end), 0, &+/2)

sumOfSquares1 = 1..100 |> Enum.map(fn x -> x * x end) |> Enum.reduce(0, &+/2)

square = fn x -> x * x endsumOfSquares2 = 1..100 |> Enum.map(square) |> Enum.sum

Page 10: Introducing Elixir

Macrosdefmodule Unless do defmacro macro_unless(clause, expression) do quote do if(!unquote(clause), do: unquote(expression)) end endend

Unless.macro_unless false, do: IO.puts "prints"Unless.macro_unless true, do: IO.puts "doesn't print"

Page 11: Introducing Elixir

Processespid = spawn fn -> receive do msg -> IO.puts "Received: #{msg}" endend

send pid, "Hello!"send pid, "3 times"

Page 12: Introducing Elixir

Supervisors

DEMO