gautema / elixir_pres

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Elixir

Gaute Magnussen

Elixir

Elixir is a functional, concurrent, general-purpose programming language that runs on the Erlang virtual machine (BEAM). Elixir builds on top of Erlang and shares the same abstractions for building distributed, fault-tolerant applications. Elixir also provides a productive tooling and an extensible design. The latter is supported by compile-time metaprogramming with macros and polymorphism via protocols.

Erlang

Erlang (/ˈɜːrlæŋ/ er-lang) is a general-purpose, concurrent, functional programming language, as well as a garbage-collected runtime system.

The term Erlang is used interchangeably with Erlang/OTP, or OTP, which consists of the Erlang runtime system, a number of ready-to-use components mainly written in Erlang, and a set of design principles for Erlang programs.

Erlang

  • Erlang - Språk
  • OTP - Sett med biblioteker og design patterns
  • BEAM - Erlang Virtual Machine

Erlang

  • Laget av Ericsson i 1986, open source 1998
  • Kjører på halvparten av alle mobilswitcher i verden.
  • Brukes av Facebook, Amazon, Heroku, Riak, Whatsapp
  • Whatsapp har 2 millioner devices koblet til hver server

Erlang

+ Ekstremt stabilt Skalerer godt horisontalt Tåler en stor mengde long running connections Hot upgrade Soft realtime - Merkelig syntaks Mye boilerplatekode Mangler muligheter fra moderne språk

Elixir

Elixir

programmers not onboard with functional programming in 5 years will be maintenance programmers

Dave Thomas, GOTO 2014

Elixir Datatyper

123 # integer
0x1F # integer
12.34 # float
"Hello world" # string
:hello # atom
[1,2,"hello"] # list
{:ok, 3, "hei"} # tuple
%{name: "Gaute", age: 35} # map
%Person{name: "Gaute", age: 35} # struct
fn(x) -> x * x end # function

Elixir Syntaks

defmodule Hello do
  def world do
    IO.puts("Hello world!")
  end

  defp priv do
    IO.puts "Can't reach this"
  end
end

Hello.world # prints "Hello world"
Hello.priv() #** (UndefinedFunctionError) function Hello.priv/0 is undefined or private

Elixir Immutable

iex(2)> x = [1,2,3]
[1, 2, 3]
iex(3)> List.delete x, 1
[2, 3]
iex(4)> x
[1, 2, 3]

Elixir Arrow

  1..110
  |> Enum.map(&(&1 * &1))
  |> Enum.sort
  |> Enum.sum

Elixir Pattern matching

 x = 1
 1 = 1
 2 = 1 # ** (MatchError) no match of right hand side value: 1
 [x,y] = [1, 2]
 [head | tail] = [1,2,3,4,5]
 {a, b, c} = {:hello, "world", 42}

 {:ok, result} = {:ok, 13}

Elixir Pattern matching

 defmodule Fibonacci do
   def fib(0), do: 0
   def fib(1), do: 1
   def fib(n), do: fib(n-1) + fib(n-2)
 end

Elixir Processes

Not os-thread

  spawn fn ->
    IO.puts("Hello from new process")
  end

Elixir Processes

lightweight

    for _ <- 1..100_000 do
      spawn(fn -> :ok end)
    end

Elixir Processes

isolation

per process GC, heap, stack

Elixir Processes

message passing

 pid = spawn(fn ->
   receive do
     {:msg,contents} -> IO.puts(contents)
   end
 end)

send(pid, "hello")

Elixir Actors

  defmodule MyActor do
    def loop(state) do
      receive do
        {from, num} ->
          new_state = state + num
          IO.puts("new state #{new_state}")
          send(from, new_state)
          loop(new_state)
      end
    end
  end

  pid = spawn fn -> MyActor.loop(1) end
  send(pid, {self(), 2})

Elixir Task

Conveniences for spawning and awaiting tasks.

task = Task.async(fn -> do_some_work() end)
res = Task.await(task)

Elixir Agent

Simple wrappers around state

{:ok, agent} = Agent.start(fn -> 0 end)
# {:ok, #PID<0.70.0>}
Agent.update(agent, &(&1+2))
# :ok
Agent.get(agent, &(&1))
# 2

Elixir GenServer

 genserver.ex

Elixir Macros

2 + 4 # {:+, 1, [2,4]}

defmacro unless(expr, opts) do
  quote do
    if(!unquote(expr), unquote(opts))
  end
end

unless true do
  ...
end

Elixir Protocols

defprotocol JSON do
  def to_json(item)
end

defimpl JSON, for: number do
  ...
end

JSON.to_json(item)

Elixir Databaser

  • ETS
  • DETS
  • Mnesia

Elixir Hot code swap

defmodule Blabber do
  def start do
    spawn( __MODULE__, :loop, [1] )
  end

  def loop( count ) do
    receive do
      :done -> IO.puts( "Closing" )
              :ok
    after
      2000 -> IO.puts( "Loop #{node()} with #{count} says hello" )
              Blabber.loop( count + 1 )
    end
  end
end

c("blabber.ex") pid = Blabber.start

Elixir Interop

# Erlang crypto algorithm
:crypto.hash(:sha256, "hash this")
# Shell command
System.cmd("whoami",[])

Elixir Tooling

  • Iex
  • Mix
  • Hex
  • ExUnit
  • dialyzer/dialyxir

Elixir Phoenix og Ecto

  • web-rammeverk
  • orm med linq support

Elixir Hvordan begynne?

brew install elixir
open http://elixir-lang.org/getting-started/introduction.html
iex

Elixir Spørsmål?

About


Languages

Language:Elixir 100.0%