Upgrade to Pro — share decks privately, control downloads, hide ads and more …

PromptWorks Talk Tuesdays: Ray Zane 1/17/17 "Elixir Is Cool"

PromptWorks Talk Tuesdays: Ray Zane 1/17/17 "Elixir Is Cool"

An introduction to some of my favorite elixir features.

https://www.promptworks.com/

PromptWorks

January 25, 2017
Tweet

More Decks by PromptWorks

Other Decks in Programming

Transcript

  1. |>

  2. x = 1 # this is the "match" operator 1

    = x # this is completely legit # lists [a, b, c] = [1, 2, 3] # maps %{id: id} = %{id: 1} %{id: id} = %{id: 1, name: "fido"} %{id: id} = %User{id: 1} # structs work too! # tuples {:ok, status, response} = {:ok, 200, "<h1>Dogs</h1>"}
  3. defmodule DogService do def run do HTTP.get("/doggies") end def log({:ok,

    response}) do Logger.info(response) end def log({:error, error}) do Logger.error(error) end def log(_) do Logger.error("uhh... what happened?") end end DogService.run |> DogService.log
  4. def give_treat(dog) do if dog do if dog.age > 5

    "here ya go, #{dog.name}" else "here ya go, pup" end else "uhhh... no dog?" end end
  5. def give_treat(nil), do: "uhh... no dog?" def give_treat(%{name: name, id:

    id}) when id > 5 do "here ya go, #{name}" end def give_treat(_) do "here ya go, pup" end
  6. def give_treat(nil), do: "uhh... no dog?" def give_treat(id) when is_integer(id)

    do id |> find |> give_treat end def give_treat(%{age: age, name: name}) when age > 5 do "here ya go, #{name}" end def give_treat(_) do "here ya go, pup" end
  7. case DB.insert(changeset) do {:ok, record} -> # woot woot! {:error,

    :timeout} -> # handle it {:error, changeset} -> # handle it end
  8. def save(changeset) do case DB.insert(changeset) do {:ok, record} -> case

    ElasticSearch.sync(record) do {:ok, _, response} -> {:ok, record, response} {:error, status, response} -> {:error, status, response} end {:error, error} -> {:error, error} end end
  9. iex> number = 13 iex> Macro.to_string(quote do: 11 + number)

    "11 + number" iex> number = 13 iex> Macro.to_string(quote do: 11 + unquote(number)) "11 + 13"
  10. defmodule Example do def iif(test, a, b) do if test,

    do: a, else: b end end Example.iif(false, IO.puts("a"), IO.puts("b")) Example.iif(true, IO.puts("a"), IO.puts("b"))
  11. defmodule Example do defmacro iif(test, a, b) do quote do

    if unquote(test), do: unquote(a), else: unquote(b) end end end Example.iif(false, IO.puts("a"), IO.puts("b")) Example.iif(true, IO.puts("a"), IO.puts("b"))
  12. b a

  13. from fish in Fish, join: fisherman in assoc(fish, :fisherman), group_by:

    fisherman.name, select: [max(fish.length), fisherman.name]