| 1 | <h2>Comments</h2> |
| 2 | <pre><code># This is a comment</code></pre> |
| 3 | |
| 4 | <h2>Atoms</h2> |
| 5 | <pre><code>:foo |
| 6 | :bar</code></pre> |
| 7 | |
| 8 | <h2>Numbers</h2> |
| 9 | <pre><code>42 |
| 10 | 0b1010 |
| 11 | 0o777 |
| 12 | 0x1F |
| 13 | 3.14159 |
| 14 | 5.2e10 |
| 15 | 100_000</code></pre> |
| 16 | |
| 17 | <h2>Strings and heredoc</h2> |
| 18 | <pre><code>'A string with \'quotes\'!' |
| 19 | "A string with \"quotes\"!" |
| 20 | "Multi-line |
| 21 | strings are supported" |
| 22 | """ "Heredoc" strings are |
| 23 | also supported. |
| 24 | """</code></pre> |
| 25 | |
| 26 | <h2>Sigils</h2> |
| 27 | <pre><code>~s"""This is a sigil |
| 28 | using heredoc delimiters""" |
| 29 | ~r/a [reg]exp/ |
| 30 | ~r(another|regexp) |
| 31 | ~w[some words]s |
| 32 | ~c<a char list></code></pre> |
| 33 | |
| 34 | <h2>Interpolation</h2> |
| 35 | <pre><code>"This is an #{:atom}" |
| 36 | ~s/#{40+2} is the answer/</code></pre> |
| 37 | |
| 38 | <h2>Function capturing</h2> |
| 39 | <pre><code>fun = &Math.zero?/1 |
| 40 | (&is_function/1).(fun) |
| 41 | fun = &(&1 + 1) |
| 42 | fun.(1) |
| 43 | fun = &List.flatten(&1, &2) |
| 44 | fun.([1, [[2], 3]], [4, 5])</code></pre> |
| 45 | |
| 46 | <h2>Module attributes</h2> |
| 47 | <pre><code>defmodule MyServer do |
| 48 | @vsn 2 |
| 49 | end |
| 50 | |
| 51 | defmodule Math do |
| 52 | @moduledoc """ |
| 53 | Provides math-related functions. |
| 54 | |
| 55 | iex> Math.sum(1, 2) |
| 56 | 3 |
| 57 | |
| 58 | """ |
| 59 | |
| 60 | @doc """ |
| 61 | Calculates the sum of two numbers. |
| 62 | """ |
| 63 | def sum(a, b), do: a + b |
| 64 | end</code></pre> |
| 65 | |
| 66 | <h2>Full example</h2> |
| 67 | <pre><code># Example from http://learnxinyminutes.com/docs/elixir/ |
| 68 | |
| 69 | # Single line comments start with a number symbol. |
| 70 | |
| 71 | # There's no multi-line comment, |
| 72 | # but you can stack multiple comments. |
| 73 | |
| 74 | # To use the elixir shell use the `iex` command. |
| 75 | # Compile your modules with the `elixirc` command. |
| 76 | |
| 77 | # Both should be in your path if you installed elixir correctly. |
| 78 | |
| 79 | ## --------------------------- |
| 80 | ## -- Basic types |
| 81 | ## --------------------------- |
| 82 | |
| 83 | # There are numbers |
| 84 | 3 # integer |
| 85 | 0x1F # integer |
| 86 | 3.0 # float |
| 87 | |
| 88 | # Atoms, that are literals, a constant with name. They start with `:`. |
| 89 | :hello # atom |
| 90 | |
| 91 | # Tuples that are stored contiguously in memory. |
| 92 | {1,2,3} # tuple |
| 93 | |
| 94 | # We can access a tuple element with the `elem` function: |
| 95 | elem({1, 2, 3}, 0) #=> 1 |
| 96 | |
| 97 | # Lists that are implemented as linked lists. |
| 98 | [1,2,3] # list |
| 99 | |
| 100 | # We can access the head and tail of a list as follows: |
| 101 | [head | tail] = [1,2,3] |
| 102 | head #=> 1 |
| 103 | tail #=> [2,3] |
| 104 | |
| 105 | # In elixir, just like in Erlang, the `=` denotes pattern matching and |
| 106 | # not an assignment. |
| 107 | # |
| 108 | # This means that the left-hand side (pattern) is matched against a |
| 109 | # right-hand side. |
| 110 | # |
| 111 | # This is how the above example of accessing the head and tail of a list works. |
| 112 | |
| 113 | # A pattern match will error when the sides don't match, in this example |
| 114 | # the tuples have different sizes. |
| 115 | # {a, b, c} = {1, 2} #=> ** (MatchError) no match of right hand side value: {1,2} |
| 116 | |
| 117 | # There are also binaries |
| 118 | <<1,2,3>> # binary |
| 119 | |
| 120 | # Strings and char lists |
| 121 | "hello" # string |
| 122 | 'hello' # char list |
| 123 | |
| 124 | # Multi-line strings |
| 125 | """ |
| 126 | I'm a multi-line |
| 127 | string. |
| 128 | """ |
| 129 | #=> "I'm a multi-line\nstring.\n" |
| 130 | |
| 131 | # Strings are all encoded in UTF-8: |
| 132 | "héllò" #=> "héllò" |
| 133 | |
| 134 | # Strings are really just binaries, and char lists are just lists. |
| 135 | <<?a, ?b, ?c>> #=> "abc" |
| 136 | [?a, ?b, ?c] #=> 'abc' |
| 137 | |
| 138 | # `?a` in elixir returns the ASCII integer for the letter `a` |
| 139 | ?a #=> 97 |
| 140 | |
| 141 | # To concatenate lists use `++`, for binaries use `<>` |
| 142 | [1,2,3] ++ [4,5] #=> [1,2,3,4,5] |
| 143 | 'hello ' ++ 'world' #=> 'hello world' |
| 144 | |
| 145 | <<1,2,3>> <> <<4,5>> #=> <<1,2,3,4,5>> |
| 146 | "hello " <> "world" #=> "hello world" |
| 147 | |
| 148 | # Ranges are represented as `start..end` (both inclusive) |
| 149 | 1..10 #=> 1..10 |
| 150 | lower..upper = 1..10 # Can use pattern matching on ranges as well |
| 151 | [lower, upper] #=> [1, 10] |
| 152 | |
| 153 | ## --------------------------- |
| 154 | ## -- Operators |
| 155 | ## --------------------------- |
| 156 | |
| 157 | # Some math |
| 158 | 1 + 1 #=> 2 |
| 159 | 10 - 5 #=> 5 |
| 160 | 5 * 2 #=> 10 |
| 161 | 10 / 2 #=> 5.0 |
| 162 | |
| 163 | # In elixir the operator `/` always returns a float. |
| 164 | |
| 165 | # To do integer division use `div` |
| 166 | div(10, 2) #=> 5 |
| 167 | |
| 168 | # To get the division remainder use `rem` |
| 169 | rem(10, 3) #=> 1 |
| 170 | |
| 171 | # There are also boolean operators: `or`, `and` and `not`. |
| 172 | # These operators expect a boolean as their first argument. |
| 173 | true and true #=> true |
| 174 | false or true #=> true |
| 175 | # 1 and true #=> ** (ArgumentError) argument error |
| 176 | |
| 177 | # Elixir also provides `||`, `&&` and `!` which accept arguments of any type. |
| 178 | # All values except `false` and `nil` will evaluate to true. |
| 179 | 1 || true #=> 1 |
| 180 | false && 1 #=> false |
| 181 | nil && 20 #=> nil |
| 182 | !true #=> false |
| 183 | |
| 184 | # For comparisons we have: `==`, `!=`, `===`, `!==`, `<=`, `>=`, `<` and `>` |
| 185 | 1 == 1 #=> true |
| 186 | 1 != 1 #=> false |
| 187 | 1 < 2 #=> true |
| 188 | |
| 189 | # `===` and `!==` are more strict when comparing integers and floats: |
| 190 | 1 == 1.0 #=> true |
| 191 | 1 === 1.0 #=> false |
| 192 | |
| 193 | # We can also compare two different data types: |
| 194 | 1 < :hello #=> true |
| 195 | |
| 196 | # The overall sorting order is defined below: |
| 197 | # number < atom < reference < functions < port < pid < tuple < list < bit string |
| 198 | |
| 199 | # To quote Joe Armstrong on this: "The actual order is not important, |
| 200 | # but that a total ordering is well defined is important." |
| 201 | |
| 202 | ## --------------------------- |
| 203 | ## -- Control Flow |
| 204 | ## --------------------------- |
| 205 | |
| 206 | # `if` expression |
| 207 | if false do |
| 208 | "This will never be seen" |
| 209 | else |
| 210 | "This will" |
| 211 | end |
| 212 | |
| 213 | # There's also `unless` |
| 214 | unless true do |
| 215 | "This will never be seen" |
| 216 | else |
| 217 | "This will" |
| 218 | end |
| 219 | |
| 220 | # Remember pattern matching? Many control-flow structures in elixir rely on it. |
| 221 | |
| 222 | # `case` allows us to compare a value against many patterns: |
| 223 | case {:one, :two} do |
| 224 | {:four, :five} -> |
| 225 | "This won't match" |
| 226 | {:one, x} -> |
| 227 | "This will match and bind `x` to `:two`" |
| 228 | _ -> |
| 229 | "This will match any value" |
| 230 | end |
| 231 | |
| 232 | # It's common to bind the value to `_` if we don't need it. |
| 233 | # For example, if only the head of a list matters to us: |
| 234 | [head | _] = [1,2,3] |
| 235 | head #=> 1 |
| 236 | |
| 237 | # For better readability we can do the following: |
| 238 | [head | _tail] = [:a, :b, :c] |
| 239 | head #=> :a |
| 240 | |
| 241 | # `cond` lets us check for many conditions at the same time. |
| 242 | # Use `cond` instead of nesting many `if` expressions. |
| 243 | cond do |
| 244 | 1 + 1 == 3 -> |
| 245 | "I will never be seen" |
| 246 | 2 * 5 == 12 -> |
| 247 | "Me neither" |
| 248 | 1 + 2 == 3 -> |
| 249 | "But I will" |
| 250 | end |
| 251 | |
| 252 | # It is common to set the last condition equal to `true`, which will always match. |
| 253 | cond do |
| 254 | 1 + 1 == 3 -> |
| 255 | "I will never be seen" |
| 256 | 2 * 5 == 12 -> |
| 257 | "Me neither" |
| 258 | true -> |
| 259 | "But I will (this is essentially an else)" |
| 260 | end |
| 261 | |
| 262 | # `try/catch` is used to catch values that are thrown, it also supports an |
| 263 | # `after` clause that is invoked whether or not a value is caught. |
| 264 | try do |
| 265 | throw(:hello) |
| 266 | catch |
| 267 | message -> "Got #{message}." |
| 268 | after |
| 269 | IO.puts("I'm the after clause.") |
| 270 | end |
| 271 | #=> I'm the after clause |
| 272 | # "Got :hello" |
| 273 | |
| 274 | ## --------------------------- |
| 275 | ## -- Modules and Functions |
| 276 | ## --------------------------- |
| 277 | |
| 278 | # Anonymous functions (notice the dot) |
| 279 | square = fn(x) -> x * x end |
| 280 | square.(5) #=> 25 |
| 281 | |
| 282 | # They also accept many clauses and guards. |
| 283 | # Guards let you fine tune pattern matching, |
| 284 | # they are indicated by the `when` keyword: |
| 285 | f = fn |
| 286 | x, y when x > 0 -> x + y |
| 287 | x, y -> x * y |
| 288 | end |
| 289 | |
| 290 | f.(1, 3) #=> 4 |
| 291 | f.(-1, 3) #=> -3 |
| 292 | |
| 293 | # Elixir also provides many built-in functions. |
| 294 | # These are available in the current scope. |
| 295 | is_number(10) #=> true |
| 296 | is_list("hello") #=> false |
| 297 | elem({1,2,3}, 0) #=> 1 |
| 298 | |
| 299 | # You can group several functions into a module. Inside a module use `def` |
| 300 | # to define your functions. |
| 301 | defmodule Math do |
| 302 | def sum(a, b) do |
| 303 | a + b |
| 304 | end |
| 305 | |
| 306 | def square(x) do |
| 307 | x * x |
| 308 | end |
| 309 | end |
| 310 | |
| 311 | Math.sum(1, 2) #=> 3 |
| 312 | Math.square(3) #=> 9 |
| 313 | |
| 314 | # To compile our simple Math module save it as `math.ex` and use `elixirc` |
| 315 | # in your terminal: elixirc math.ex |
| 316 | |
| 317 | # Inside a module we can define functions with `def` and private functions with `defp`. |
| 318 | # A function defined with `def` is available to be invoked from other modules, |
| 319 | # a private function can only be invoked locally. |
| 320 | defmodule PrivateMath do |
| 321 | def sum(a, b) do |
| 322 | do_sum(a, b) |
| 323 | end |
| 324 | |
| 325 | defp do_sum(a, b) do |
| 326 | a + b |
| 327 | end |
| 328 | end |
| 329 | |
| 330 | PrivateMath.sum(1, 2) #=> 3 |
| 331 | # PrivateMath.do_sum(1, 2) #=> ** (UndefinedFunctionError) |
| 332 | |
| 333 | # Function declarations also support guards and multiple clauses: |
| 334 | defmodule Geometry do |
| 335 | def area({:rectangle, w, h}) do |
| 336 | w * h |
| 337 | end |
| 338 | |
| 339 | def area({:circle, r}) when is_number(r) do |
| 340 | 3.14 * r * r |
| 341 | end |
| 342 | end |
| 343 | |
| 344 | Geometry.area({:rectangle, 2, 3}) #=> 6 |
| 345 | Geometry.area({:circle, 3}) #=> 28.25999999999999801048 |
| 346 | # Geometry.area({:circle, "not_a_number"}) |
| 347 | #=> ** (FunctionClauseError) no function clause matching in Geometry.area/1 |
| 348 | |
| 349 | # Due to immutability, recursion is a big part of elixir |
| 350 | defmodule Recursion do |
| 351 | def sum_list([head | tail], acc) do |
| 352 | sum_list(tail, acc + head) |
| 353 | end |
| 354 | |
| 355 | def sum_list([], acc) do |
| 356 | acc |
| 357 | end |
| 358 | end |
| 359 | |
| 360 | Recursion.sum_list([1,2,3], 0) #=> 6 |
| 361 | |
| 362 | # Elixir modules support attributes, there are built-in attributes and you |
| 363 | # may also add custom ones. |
| 364 | defmodule MyMod do |
| 365 | @moduledoc """ |
| 366 | This is a built-in attribute on a example module. |
| 367 | """ |
| 368 | |
| 369 | @my_data 100 # This is a custom attribute. |
| 370 | IO.inspect(@my_data) #=> 100 |
| 371 | end |
| 372 | |
| 373 | ## --------------------------- |
| 374 | ## -- Structs and Exceptions |
| 375 | ## --------------------------- |
| 376 | |
| 377 | # Structs are extensions on top of maps that bring default values, |
| 378 | # compile-time guarantees and polymorphism into Elixir. |
| 379 | defmodule Person do |
| 380 | defstruct name: nil, age: 0, height: 0 |
| 381 | end |
| 382 | |
| 383 | joe_info = %Person{ name: "Joe", age: 30, height: 180 } |
| 384 | #=> %Person{age: 30, height: 180, name: "Joe"} |
| 385 | |
| 386 | # Access the value of name |
| 387 | joe_info.name #=> "Joe" |
| 388 | |
| 389 | # Update the value of age |
| 390 | older_joe_info = %{ joe_info | age: 31 } |
| 391 | #=> %Person{age: 31, height: 180, name: "Joe"} |
| 392 | |
| 393 | # The `try` block with the `rescue` keyword is used to handle exceptions |
| 394 | try do |
| 395 | raise "some error" |
| 396 | rescue |
| 397 | RuntimeError -> "rescued a runtime error" |
| 398 | _error -> "this will rescue any error" |
| 399 | end |
| 400 | |
| 401 | # All exceptions have a message |
| 402 | try do |
| 403 | raise "some error" |
| 404 | rescue |
| 405 | x in [RuntimeError] -> |
| 406 | x.message |
| 407 | end |
| 408 | |
| 409 | ## --------------------------- |
| 410 | ## -- Concurrency |
| 411 | ## --------------------------- |
| 412 | |
| 413 | # Elixir relies on the actor model for concurrency. All we need to write |
| 414 | # concurrent programs in elixir are three primitives: spawning processes, |
| 415 | # sending messages and receiving messages. |
| 416 | |
| 417 | # To start a new process we use the `spawn` function, which takes a function |
| 418 | # as argument. |
| 419 | f = fn -> 2 * 2 end #=> #Function<erl_eval.20.80484245> |
| 420 | spawn(f) #=> #PID<0.40.0> |
| 421 | |
| 422 | # `spawn` returns a pid (process identifier), you can use this pid to send |
| 423 | # messages to the process. To do message passing we use the `send` operator. |
| 424 | # For all of this to be useful we need to be able to receive messages. This is |
| 425 | # achieved with the `receive` mechanism: |
| 426 | defmodule Geometry do |
| 427 | def area_loop do |
| 428 | receive do |
| 429 | {:rectangle, w, h} -> |
| 430 | IO.puts("Area = #{w * h}") |
| 431 | area_loop() |
| 432 | {:circle, r} -> |
| 433 | IO.puts("Area = #{3.14 * r * r}") |
| 434 | area_loop() |
| 435 | end |
| 436 | end |
| 437 | end |
| 438 | |
| 439 | # Compile the module and create a process that evaluates `area_loop` in the shell |
| 440 | pid = spawn(fn -> Geometry.area_loop() end) #=> #PID<0.40.0> |
| 441 | |
| 442 | # Send a message to `pid` that will match a pattern in the receive statement |
| 443 | send pid, {:rectangle, 2, 3} |
| 444 | #=> Area = 6 |
| 445 | # {:rectangle,2,3} |
| 446 | |
| 447 | send pid, {:circle, 2} |
| 448 | #=> Area = 12.56000000000000049738 |
| 449 | # {:circle,2} |
| 450 | |
| 451 | # The shell is also a process, you can use `self` to get the current pid |
| 452 | self() #=> #PID<0.27.0></code></pre> |