1
0

sample.elixir.txt 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. # Elixir is a dynamic, functional language for building scalable
  2. # and maintainable applications. Learn more: https://elixir-lang.org
  3. "Elixir" |> String.graphemes() |> Enum.frequencies()
  4. #=> %{"E" => 1, "i" => 2, "l" => 1, "r" => 1, "x" => 1}
  5. ### Scalability ###
  6. # All Elixir code runs inside lightweight threads of execution (called processes)
  7. # that are isolated and exchange information via messages:
  8. current_process = self()
  9. # Spawn an Elixir process (not an operating system one!)
  10. spawn_link(fn ->
  11. send(current_process, {:msg, "hello world"})
  12. end)
  13. # Block until the message is received
  14. receive do
  15. {:msg, contents} -> IO.puts(contents)
  16. end
  17. ### Fault-tolerance ###
  18. # To cope with failures, Elixir provides supervisors which describe
  19. # how to restart parts of your system when things go awry, going back
  20. # to a known initial state that is guaranteed to work:
  21. children = [
  22. TCP.Pool,
  23. {TCP.Acceptor, port: 4040}
  24. ]
  25. Supervisor.start_link(children, strategy: :one_for_one)
  26. ### Functional programming ###
  27. # Functional programming promotes a coding style that helps
  28. # developers write code that is short, concise, and maintainable.
  29. # One prominent example is pattern matching:
  30. %User{name: name, age: age} = User.get("John Doe")
  31. name #=> "John Doe"
  32. # When mixed with guards, pattern matching allows us to elegantly
  33. # match and assert specific conditions for some code to execute:
  34. def drive(%User{age: age}) when age >= 16 do
  35. # Code that drives a car
  36. end
  37. drive(User.get("John Doe"))
  38. #=> Fails if the user is under 16
  39. ### Extensibility and DSLs ###
  40. # Elixir has been designed to be extensible, letting developers
  41. # naturally extend the language to particular domains,
  42. # in order to increase their productivity.
  43. defmodule MathTest do
  44. use ExUnit.Case, async: true
  45. test "can add two numbers" do
  46. assert 1 + 1 == 2
  47. end
  48. end
  49. ### Erlang compatible ###
  50. # An Elixir programmer can invoke any Erlang function with no runtime cost:
  51. :crypto.hash(:md5, "Using crypto from Erlang OTP")
  52. #=> <<192, 223, 75, 115, ...>>