Intro to Elixir
May 24, 2015
Intro to Elixir
Drew Olson Braintree
brew install elixir
Functional Concurrent Immutable
Erlang?
Kind of. It’s on the Erlang VM.
Metaprogramming Polymorphism
Tooling
IO.puts "Hello, world!"
Types
1 # integer"1.0 # float":atom # atom / symbol"{1, 2, 3} # tuple"[1, 2, 3] # list
[name: "Drew", age: 31] # keyword"[{:name, "Drew"}, {:age, 31}] # keyword
HashDict.new(name: "Drew", age: 31) # HashDict
Modules & Functions
defmodule Greeter do" def greet(thing) do" IO.puts "Hello, #{thing}!"" end"end"!
Greeter.greet("World")
Anonymous Functions
subject = "World""!
greeter = fn(greeting) ->" IO.puts("#{greeting}, #{subject}!")"end"!
greeter.("Hello")
Records
defrecord Person," name: nil," age: nil"!
drew = Person.new(name: "Drew", age: 31)"!
IO.puts(drew.name)"IO.puts(drew.age)
Protocols
defprotocol Checker do" @fallback_to_any true" def person?(data)"end"!defimpl Checker, for: Person do" def person?(_) do" true" end"end"!defimpl Checker, for: Any do" def person?(_) do" false" end"end"!Checker.person?(Person.new)"Checker.person?(HashDict.new)
Enum
list = [1, 2, 3]"keyword = [a: 1, b: 2, c: 3]"!
Enum.map list, fn(item) ->" item * 2"end"!
Enum.map keyword, fn({key, val}) ->" "#{key} -> #{val}""end
Pattern Matching
list = [1, 2, 3]"!
case list do" [head|_] ->" IO.puts(head)" [] ->" IO.puts("empty!")"end
defmodule MyList do" def sum(list) do" sum(list, 0)" end"!
defp sum([head|rest], acc) do" sum(rest, acc + head)" end"!
defp sum([], acc) do" acc" end"end"!
MyList.sum([1, 2, 3])
but really
Enum.reduce [1, 2, 3], fn(item, acc) ->" acc + item"end
Macros
not today :)
Concurrency
not today ;(
Tooling
mix
Bundler + Rake
defmodule Foo.Mixfile do" use Mix.Project"! def project do" [ app: :foo," version: "0.0.1"," elixir: "~> 0.12.2"," deps: deps ]" end"! # Configuration for the OTP application" def application do" [mod: { Foo, [] }]" end"! # Returns the list of dependencies in the format:" # { :foobar, git: "https://github.com/elixir-lang/foobar.git", tag: "0.1" }" #" # To specify particular versions, regardless of the tag, do:" # { :barbat, "~> 0.1", github: "elixir-lang/barbat" }" defp deps do" []" end"end
ExUnit
defmodule MyListTest do" use ExUnit.Case"!
test "it sums" do" assert MyList.sum([1, 2, 3]) == 6" end"end
Demos
Thank you. Questions?