20 message = "Hello, " <> name <> "!"
25 Greeter.greet("world")
50 IO.puts "Hello, " <> user.name
57 users = [ "Tom", "Dick", "Harry" ]
62 Enum.map(users, fn user ->
63 IO.puts "Hello " <> user
78 print(transform(source, :hello))
81 These two are equivalent.
86 user = %{name: "Tom", age: 23}
87 %{name: username} = user
91 This sets `username` to `"Tom"`.
93 ### Pattern matching in functions
96 def greet(%{name: username}) do
97 IO.puts "Hello, " <> username
100 user = %{name: "Tom", age: 23}
104 Pattern matching works in function parameters too.
114 "This will never be seen"
124 "This clause won't match"
126 "This will match and bind x to 2"
128 "This will match any value"
137 "I will never be seen"
141 "But I will (this is essentially an else)"
151 message -> "Got #{message}."
153 IO.puts("I'm the after clause.")
164 | `true` _/_ `false` | Boolean |
166 | `?a` | Integer (ASCII) |
170 | `'hello'` | Charlist |
171 | `<<2, 3>>` | Binary |
172 | `"hello"` | Binary string |
178 | `%{a: "hello"}` | Map |
179 | `%MyStruct{a: "hello"}` | Struct |
180 | `fn -> ... end` | Function |
212 left != right # equal
213 left !== right # match
214 left ++ right # concat lists
215 left <> right # concat string/binary
216 left =~ right # regexp
225 require Redux # compiles a module
226 import Redux # compiles, and you can use without the `Redux.` prefix
228 use Redux # compiles, and runs Redux.__using__/1
229 use Redux, async: true
231 import Redux, only: [duplicate: 2]
232 import Redux, only: :functions
233 import Redux, only: :macros
235 import Foo.{Bar, Baz}
241 alias Foo.Bar, as: Bar
242 alias Foo.Bar # same as above
258 str |> length() # → 5
259 str |> codepoints() # → ["h", "e", "l", "l", "o"]
260 str |> slice(2..-1) # → "llo"
261 str |> split(" ") # → ["hello"]
262 str |> capitalize() # → "Hello"
266 ### Inspecting objects
269 inspect(object, opts \\ [])
272 value |> IO.inspect()
275 value |> IO.inspect(label: "value")
285 rem(a, b) # remainder (modulo)
286 div(a, b) # integer division
303 n |> ceil(2) # → 11.30
304 n |> to_string() # → "1.030000+e01"
305 n |> to_string([decimals: 2, compact: true])
309 Float.parse("34") # → { 34.0, "" }
325 n |> digits() # → [1, 2]
326 n |> to_charlist() # → '12'
327 n |> to_string() # → "12"
334 n |> digits(2) # → [1, 1, 0, 0]
335 n |> to_charlist(2) # → '1100'
336 n |> to_string(2) # → "1100"
340 parse("12") # → {12, ""}
341 undigits([1, 2]) # → 12
347 Float.parse("34.1") # → {34.1, ""}
348 Integer.parse("34") # → {34, ""}
352 Float.to_string(34.1) # → "3.4100e+01"
353 Float.to_string(34.1, [decimals: 2, compact: true]) # → "34.1"
361 m = %{name: "hi"} # atom keys (:name)
362 m = %{"name" => "hi"} # string keys ("name")
373 m = %{m | name: "yo"} # key must exist
377 m |> put(:id, 2) # → %{id: 2, name: "hi"}
378 m |> put_new(:id, 2) # only if `id` doesn't exist (`||=`)
382 m |> put(:b, "Banana")
383 m |> merge(%{b: "Banana"})
384 m |> update(:a, &(&1 + 1))
385 m |> update(:a, fun a -> a + 1 end)
389 m |> get_and_update(:a, &(&1 || "default"))
396 m |> delete(:name) # → %{}
397 m |> pop(:name) # → {"John", %{}}
404 m |> keys() # → [:id, :name]
405 m |> values() # → [1, "hi"]
409 m |> to_list() # → [id: 1, name: "hi"]
410 # → [{:id, 1}, {:name, "hi"}]
416 put_in(map, [:b, :c], "Banana")
417 put_in(map[:b][:c], "Banana") # via macros
421 get_and_update_in(users, ["john", :age], &{&1, &1 + 1})
424 ### Constructing from lists
427 Map.new([{:b, 1}, {:a, 2}])
428 Map.new([a: 1, b: 2])
429 Map.new([:a, :b], fn x -> {x, x} end) # → %{a: :a, b: :b}
445 l = l ++ [5] # push (append)
446 l = [ 0 | list ] # unshift (prepend)
459 Also see [Enum](#enum).
478 list |> count() # → 3
479 list |> empty?() # → false
480 list |> any?() # → true
484 list |> concat([:d]) # → [:a, :b, :c, :d]
487 Also, consider streams instead.
493 list |> reduce(acc, fn)
502 |> Enum.reduce(0, fn(x, acc) -> x + acc end)
519 t |> elem(1) # like tuple[1]
520 t |> put_elem(index, value)
527 list = [{ :name, "John" }, { :age, 15 }]
532 # For string-keyed keyword lists
533 list = [{"size", 2}, {"type", "shoe"}]
534 List.keyfind(list, "size", 0) # → {"size", 2}
542 square = fn n -> n*n end
552 square = &Math.square/1
560 apply(module, fun, args)
566 def join(a, b \\ nil)
567 def join(a, b) when is_nil(b) do: a
568 def join(a, b) do: a <> b
577 defstruct name: "", age: nil
580 %User{name: "John", age: 20}
582 %User{}.struct # → User
585 See: [Structs](http://elixir-lang.org/getting-started/structs.html)
589 ### Defining protocols
593 @doc "Returns true if data is considered blank/empty"
599 defimpl Blank, for: List do
600 def blank?([]), do: true
601 def blank?(_), do: false
604 Blank.blank?([]) # → true
610 defimpl Blank, for: Any do ... end
613 @derive Blank # Falls back to Any
620 - `Enumerable` and `Enum.map()`
621 - `Inspect` and `inspect()`
628 for n <- [1, 2, 3, 4], do: n * n
629 for n <- 1..4, do: n * n
633 for {key, val} <- %{a: 10, b: 20}, do: val
638 for {key, val} <- %{a: 10, b: 20}, into: %{}, do: {key, val*val}
644 for n <- 1..10, rem(n, 2) == 0, do: n
652 file <- File.ls!(dir), # nested comprehension
653 path = Path.join(dir, file), # invoked
654 File.regular?(path) do # condition
667 @after_compile __MODULE__
668 def __before_compile__(env)
669 def __after_compile__(env, _bytecode)
670 def __using__(opts) # invoked on `use`
672 @on_definition {__MODULE__, :on_def}
673 def on_def(_env, kind, name, args, guards, body)
692 ~s|strings with #{interpolation} and \x20 escape codes|
693 ~S|no interpolation and no escapes|
697 Allowed chars: `/` `|` `"` `'` `(` `[` `{` `<` `"""`.
698 See: [Sigils](http://elixir-lang.org/getting-started/sigils.html)
703 @spec round(number) :: integer
705 @type number_with_remark :: {number, String.t}
706 @spec add(number, number) :: number_with_remark
709 Useful for [dialyzer](http://www.erlang.org/doc/man/dialyzer.html).
710 See: [Typespecs](http://elixir-lang.org/getting-started/typespecs-and-behaviours.html)
716 @callback parse(String.t) :: any
717 @callback extensions() :: [String.t]
722 defmodule JSONParser do
725 def parse(str), do: # ... parse JSON
726 def extensions, do: ["json"]
730 See: [Module](http://elixir-lang.org/docs/stable/elixir/Module.html)
735 - [Learn Elixir in Y minutes](https://learnxinyminutes.com/docs/elixir/)