Add some code samples.
[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 IO.puts "=== Binary ==="
22 str = "hëllö" <> <<0>> # Append a zero to the string (binary).
23 IO.inspect str, binaries: :as_binaries
24
25 IO.inspect(<<3::4>> === <<0::1, 0::1, 1::1, 1::1>>) # Same binaries: 3 encoded on 4 bits.
26 IO.inspect(is_binary <<0xFF, 0x5A>>) # true.
27 IO.inspect(is_binary <<0xFF, 0xF::4>>) # false: binaries must be on a multiple of 8 bits.
28 IO.inspect(is_bitstring <<0xFF, 0xF::4>>) # true.
29
30 # Pattern matching on binaries.
31 <<x::utf8, rest::binary>> = "über"
32 IO.inspect(x === ?ü) # true.
33
34 # 'charlist': the string in Erlang.
35 IO.puts "=== charlist ==="
36 IO.inspect('hëllò', charlists: :as_lists)
37 IO.inspect(to_string('hëllò') == "hëllò") # true.
38 IO.inspect('hëllò' == to_charlist("hëllò")) # true.
39
40 # keyword list.
41 IO.puts "=== keyword list ==="
42 IO.inspect([{:a, 1}, {:b, 2}] === [a: 1, b: 2]) # true.
43 IO.inspect(a: 1, b: 2, c: 3) # Brackets omitted.
44
45 # Maps.
46 IO.puts "=== Map ==="
47 map = %{:a => 1, 2 => :b}
48 IO.inspect map[:a] # Print 1.
49 IO.inspect map.a # Special syntax with atom key, print 1.
50 IO.inspect map[2] # Print ':b'.
51 IO.inspect map[3] # Print 'nil'.
52 %{:a => a} = map
53 IO.inspect a # Print 1.
54 IO.inspect %{map | 2 => "two"} # Updating 'map'.
55
56 # Module.
57 IO.puts "=== Module ==="
58 defmodule Math do
59     def sum(a, b) do
60         a + b
61     end
62
63     def zero?(0), do: true
64     def zero?(x) when is_integer(x), do: false
65 end
66
67 IO.inspect Math.sum(1, 2)
68 IO.inspect Math.zero?(1)
69
70 fun = &Math.zero?/1 # '&' to capture a function as a lambda (and use with high level functions).
71 IO.inspect fun.(0) # Calling it with same syntaxe as lambdas.
72
73 fun2 = &(&1 + 1) # Shortcut syntax: '&1' is the first parameter.
74 fun3 = &"Good #{&1}"
75 IO.inspect fun2.(3) # Print 4.
76
77 # Enum.
78 IO.puts "=== Enum ==="
79 IO.inspect Enum.map([1, 2, 3], &(2 * &1))
80 IO.inspect Enum.map(%{1 => 2, 3 => 4}, fn {k, v} -> k * v end)
81 IO.inspect Enum.map(1..10, &(3 * &1))
82 IO.inspect Enum.reduce(1..3, 0, &+/2) # 1 + 2 + 3.
83
84 odd? = &(rem(&1, 2) != 0)
85 IO.inspect 1..100_000 |> Enum.map(&(3 * &1)) |> Enum.filter(odd?) |> Enum.sum
86
87 # Process.
88 IO.puts "=== Process ==="
89 pid =
90     spawn fn ->
91         receive do
92             {:hello, sender, msg} ->
93                 IO.puts "Message received: '#{msg}'"
94                 send sender, :ok
95         end
96     end
97
98
99 send pid, {:hello, self(), "Salut"}
100 receive do
101     :ok -> IO.puts "Message delivered!"
102 after
103     1_000 -> IO.puts "Message not delivered :("
104 end
105
106 IO.puts "=== State ==="
107 defmodule KV do # Key-Value.
108     def stark_link do
109         Task.start_link(fn -> loop %{} end)
110     end
111
112     defp loop(map) do
113         receive do
114             {:get, key, caller} ->
115                 send caller, Map.get(map, key)
116                 loop map
117             {:put, key, value} ->
118                 loop Map.put(map, key, value)
119         end
120     end
121 end
122
123 {:ok, kv} = KV.stark_link
124 send kv, {:put, :a, 42}
125 send kv, {:put, :b, 420}
126 send kv, {:get, :b, self()}
127 receive do
128     value -> IO.puts "Value received: #{value}"
129 end
130
131 IO.puts "=== Agent ==="
132 {:ok, pid} = Agent.start_link(fn -> %{} end)
133 Agent.update(pid, fn map -> Map.put(map, :hello, :world) end)
134 IO.inspect Agent.get(pid, fn map -> Map.get(map, :hello) end)