Upload
abdulsattar-mohammed
View
212
Download
0
Embed Size (px)
Citation preview
ElixirAbdulsattar - http://bimorphic.com
FeaturesDynamicFunctionalPattern MatchingRuby inspired syntaxExtensible: macrosConcurrency, Distributed and Fault tolerant
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
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
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))
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}
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
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
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
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"
Processespid = spawn fn -> receive do msg -> IO.puts "Received: #{msg}" endend
send pid, "Hello!"send pid, "3 times"
Supervisors
DEMO