Cheatsheet
[Elixir.git] / sandbox.exs
1 IO.inspect [1, 2, true, "abc"] ++ [3, 2, "abc"] # Concatenate two lists.
2 IO.inspect [1, 2, true, "abc"] -- [3, 2, "abc"] # List subtraction.
3 IO.inspect(hd [1, 2, 3]) # Head of a list.
4 IO.inspect(tl [1, 2, 3]) # Tail of a list.
5
6 tuple = {:ok, "hello"}
7 IO.inspect(elem tuple, 1) # Get the second element of a tuple.
8
9 IO.inspect "ABC" <> "XYZ" # String concatenation.
10
11 l = [1, 2, 3]
12 [h | t] = l
13 IO.inspect {h, t}
14 IO.inspect [0 | l]
15 a = 2
16 {^a, b} = {2, 42} # Pin operator.
17 IO.inspect b, label: "b"
18 {x, x} = {10, 10} # 'x' must be bind to the same value.
19 IO.inspect x, label: "x"
20
21 str = "hëllö" <> <<0>> # Append a zero to the string (binary).
22 IO.inspect str, binaries: :as_binaries
23
24 IO.inspect(<<3::4>> === <<0::1, 0::1, 1::1, 1::1>>) # Same binaries: 3 encoded on 4 bits.
25 IO.inspect(is_binary <<0xFF, 0x5A>>) # true.
26 IO.inspect(is_binary <<0xFF, 0xF::4>>) # false: binaries must be on a multiple of 8 bits.
27 IO.inspect(is_bitstring <<0xFF, 0xF::4>>) # true.
28
29 # Pattern matching on binaries.
30 <<x::utf8, rest::binary>> = "über"
31 IO.inspect(x === ?ü) # true.
32
33 # 'charlist': the string in Erlang.
34 IO.inspect('hëllò', charlists: :as_lists)
35 IO.inspect(to_string('hëllò') == "hëllò") # true.
36 IO.inspect('hëllò' == to_charlist("hëllò")) # true.
37
38 # keyword list.
39 IO.inspect([{:a, 1}, {:b, 2}] === [a: 1, b: 2]) # true.
40 IO.inspect(a: 1, b: 2, c: 3) # Brackets omitted.
41
42 # Maps.
43 map = %{:a => 1, 2 => :b}
44 IO.inspect map[:a] # Print 1.
45 IO.inspect map.a # Special syntax with atom key, print 1.
46 IO.inspect map[2] # Print ':b'.
47 IO.inspect map[3] # Print 'nil'.
48 %{:a => a} = map
49 IO.inspect a # Print 1.
50 IO.inspect %{map | 2 => "two"} # Updating 'map'.
51
52 # Module.
53 defmodule Math do
54     def sum(a, b) do
55         a + b
56     end
57 end
58
59 IO.inspect Math.sum(1, 2)