by @tednaleid
iex> my_utf8_string = "hello Iñtërnâtiônàlizætiøn""hello Iñtërnâtiônàlizætiøn"iex> my_atom = :hello:helloiex> 1000 == 1_000trueiex> 0.314159e1 == 314159.0e-5trueiex> my_range = 1..51..5
iex> my_tuple = {:ok, "return value", 715}{:ok, "return value", 715}iex> my_list = [1, 2, 3, 4, 5][1, 2, 3, 4, 5]iex> my_map = %{:first => "Ted", :last => "Naleid"}%{first: "Ted", last: "Naleid"}
iex> sum = fn a, b -> a + b end#Function<12.90072148/2 in :erl_eval.expr/5>iex> sum.(1, 2)3# shortened closure syntax:iex> short_sum = &(&1 + &2)&:erlang.+/2iex> short_sum.(1, 2)3
iex> defmodule Person do...> defstruct first: "Ted", last: "Naleid"...> end{:module, Person, …}iex> %Person{}%Person{first: "Ted", last: "Naleid"}iex> %Person{first: "Hazel"}%Person{first: "Hazel", last: "Naleid"}iex> %Person{nope: "Bad Field"}** (CompileError) iex:4: unknown key :nope for struct
iex> defprotocol Stringable do...> def to_string(value)...> endiex> defimpl Stringable, for: Person do...> def to_string(value) do...> "#{value.first} #{value.last}"...> end...> endiex> Stringable.to_string(%Person{})"Ted Naleid"
iex> a = {:ok, 1}{:ok, 1}iex> {:ok, b} = {:ok, 1}{:ok, 1}iex> b1
iex> [a, b, c] = [1, 2, 3][1, 2, 3]iex> a1iex> [head | tail] = [1, 2, 3][1, 2, 3]iex> head1iex> tail[2, 3]
case HTTP.get(url) do{:ok, %HTTP.Resp{ status: 200, body: body }} ->IO.puts body{:ok, %HTTP.Resp{ status: 404 }} ->IO.puts "Not found :("{:ok, %HTTP.Resp{ status: status }} ->IO.puts "HTTP Status: #{status}"{:error, %HTTP.Error{ reason: reason }} ->IO.inspect reason_ ->IO.puts "¯\_(ツ)_/¯"end
def execute({:ok, good_value}) doIO.puts "Known good value: #{good_value}"enddef execute({:error, error_reason}) doIO.puts "Error! #{error_reason}"endiex> execute({:ok, "Yay!"})Known good value: Yay!iex> execute({:error, "Boo!"})Error! Boo!
|>defmodule Shop dodefp apply_tax(prices) doEnum.map(prices, fn v -> v * 1.1 end)enddef cart_total(items) doEnum.sum(apply_tax(Enum.map(items, fn item -> item.price end)))endendShop.cart_total([%{:price=>5.00}, %{:price=>2.00}])# => 7.7
Nested cart_total is hard to read, have to read inside out
|>def cart_total(items) doprices = Enum.map(items, fn itm -> itm.price end)prices_with_tax = apply_tax(prices)Enum.sum(prices_with_tax)end
Intermediate variables cleans up a bit
|>def cart_total(items) doitems|> Enum.map(fn item -> item.price end)|> add_tax|> Enum.sumend
|> operator passes result from last method as first param in next
Similar to unix pipe: ps ax | grep iex | awk '{ print $1 }'
iex> :crypto.md5("sekr1t")<<192, 151, 240, 131, 252, 86, 1, 90, 71, 171, 2, …
Can easily leverage 20+ years of Erlang libraries
$ mix new myapp* creating README.md* creating .gitignore* creating mix.exs* creating config* creating config/config.exs* creating lib* creating lib/myapp.ex* creating test* creating test/test_helper.exs* creating test/myapp_test.exsYour mix project was created successfully.You can use mix to compile it, test it, and more:cd myappmix testRun `mix help` for more commands.
defmodule MyProject.Mixfile douse Mix.Projectdef project do[app: :myapp,version: "0.0.1",elixir: "~> 1.0",deps: deps]enddef application do[applications: [:logger]]enddefp deps do[{:ecto, "~> 0.11.3"},{:postgrex, "~> 0.8.1"},{:cowboy, github: "extend/cowboy"}]endend
iex is a Great REPLiex> h Enum.map<tab>map/2 map_join/3 map_reduce/3iex> h Enum.map/2def map(collection, fun)Returns a new collection, where each item is the result of invoking funon each corresponding item of collection.For dicts, the function expects a key-value tuple.Examples┃ iex> Enum.map([1, 2, 3], fn(x) -> x * 2 end)┃ [2, 4, 6]┃┃ iex> Enum.map([a: 1, b: 2], fn({k, v}) -> {k, -v} end)┃ [a: -1, b: -2]
pryrequire IExdef index(conn, _params) doIEx.pryconn |> render "index"end
Similar to the JavaScript debugger; command
iex> :observer.start
defmacro unless(expr, opts) doquote doif(!unquote(expr), unquote(opts))endendunless true doIO.puts "this will never be seen"end
iex> ast = quote, do 2 * 2 / 7{:/,[context: Elixir, import: Kernel],[{:*,[context: Elixir, import: Kernel], [2, 2]}, 7]}
Underlying AST looks a bit like a lisp
At time of Facebook acquisition for $19 Billion
(~0.15 load, from https://twitter.com/emjii/status/591240463782391808)
iex> parent = self()#PID<0.90.0>iex> spawn(fn -> send parent, "hello world" end)#PID<0.93.0>iex> receive do message -> IO.puts message endhello world:ok