### Agent.start/2 example Source: https://elixir.hexdocs.pm/Agent.html IEx example showing how to start an agent with an initial state and retrieve it using Agent.get/2. ```elixir iex> {:ok, pid} = Agent.start(fn -> 42 end) iex> Agent.get(pid, fn state -> state end) 42 ``` -------------------------------- ### Agent.start_link/2 example Source: https://elixir.hexdocs.pm/Agent.html IEx example showing successful start and retrieval, and a failure case where the function raises an error. ```elixir iex> {:ok, pid} = Agent.start_link(fn -> 42 end) iex> Agent.get(pid, fn state -> state end) 42 iex> {:error, {exception, _stacktrace}} = Agent.start(fn -> raise "oops" end) iex> exception %RuntimeError{message: "oops"} ``` -------------------------------- ### Agent stop/3 example Source: https://elixir.hexdocs.pm/Agent.html IEx example showing how to start an agent and stop it, returning :ok. ```elixir iex> {:ok, pid} = Agent.start_link(fn -> 42 end) iex> Agent.stop(pid) :ok ``` -------------------------------- ### Node.start example Source: https://elixir.hexdocs.pm/Node.md Example of starting a distributed node with Node.start/2, using the :shortnames name domain and hidden: true. Returns {:ok, pid} on success. ```elixir {:ok, pid} = Node.start(:example, name_domain: :shortnames, hidden: true) ``` -------------------------------- ### Start a single DynamicSupervisor Source: https://elixir.hexdocs.pm/PartitionSupervisor.md Baseline setup: starts one DynamicSupervisor named MyApp.DynamicSupervisor under a Supervisor with :one_for_one strategy. ```elixir children = [ {DynamicSupervisor, name: MyApp.DynamicSupervisor} ] Supervisor.start_link(children, strategy: :one_for_one) ``` -------------------------------- ### Range.size/1 examples Source: https://elixir.hexdocs.pm/Range.html Examples of using Range.size/1 to get the number of elements in ranges with various steps. Note that ranges with a step that does not align with the start and end can produce zero or reduced sizes. ```elixir iex> Range.size(1..10) 10 iex> Range.size(1..10//2) 5 iex> Range.size(1..10//3) 4 iex> Range.size(1..10//-1) 0 iex> Range.size(10..1//-1) 10 iex> Range.size(10..1//-2) 5 iex> Range.size(10..1//-3) 4 iex> Range.size(10..1//1) 0 ``` -------------------------------- ### start_link examples Source: https://elixir.hexdocs.pm/Agent.md IEx examples showing successful start_link and error handling when the function raises. ```elixir iex> {:ok, pid} = Agent.start_link(fn -> 42 end) iex> Agent.get(pid, fn state -> state end) 42 ``` ```elixir iex> {:error, {exception, _stacktrace}} = Agent.start(fn -> raise "oops" end) iex> exception %RuntimeError{message: "oops"} ``` -------------------------------- ### Date.day_of_week/2 usage examples Source: https://elixir.hexdocs.pm/Date.html Examples of calling Date.day_of_week/2 with various dates and starting weekdays, demonstrating the default Monday start and the :sunday option. ```elixir # 2016-10-31 is a Monday and by default Monday is the first day of the week iex> Date.day_of_week(~D[2016-10-31]) 1 iex> Date.day_of_week(~D[2016-11-01]) 2 iex> Date.day_of_week(~N[2016-11-01 01:23:45]) 2 iex> Date.day_of_week(~D[-0015-10-30]) 3 # 2016-10-31 is a Monday but, as we start the week on Sunday, now it returns 2 iex> Date.day_of_week(~D[2016-10-31], :sunday) 2 iex> Date.day_of_week(~D[2016-11-01], :sunday) 3 iex> Date.day_of_week(~N[2016-11-01 01:23:45], :sunday) 3 iex> Date.day_of_week(~D[-0015-10-30], :sunday) 4 ``` -------------------------------- ### iterate example Source: https://elixir.hexdocs.pm/Stream.md Example showing iterate doubling values starting from 1. ```elixir iex> Stream.iterate(1, &(&1 * 2)) |> Enum.take(5) [1, 2, 4, 8, 16] ``` -------------------------------- ### mkdir! examples Source: https://elixir.hexdocs.pm/File.md Examples showing mkdir! returning :ok for a successful creation and raising a File.Error when a parent directory is missing. ```elixir File.mkdir!("test/unit") #=> :ok ``` ```elixir File.mkdir!("non/existing") ** (File.Error) could not make directory "non/existing": no such file or directory ``` -------------------------------- ### Process.demonitor/2 example Source: https://elixir.hexdocs.pm/Process.md Example showing how to create a monitor and then demonitor it, returning true. ```elixir pid = spawn(fn -> 1 + 2 end) ref = Process.monitor(pid) Process.demonitor(ref) #=> true ``` -------------------------------- ### URI.default_port/1 examples Source: https://elixir.hexdocs.pm/URI.html Examples of getting default ports for known and unknown schemes. ```elixir iex> URI.default_port("ftp") 21 iex> URI.default_port("ponzi") nil ``` -------------------------------- ### Example config/runtime.exs for :my_app Source: https://elixir.hexdocs.pm/Application.html Example configuration file for an OTP application :my_app, defining database configurations and a list of repositories. ```elixir config :my_app, Databases.RepoOne, # A database configuration ip: "localhost", port: 5433 config :my_app, Databases.RepoTwo, # Another database configuration (for the same OTP app) ip: "localhost", port: 20_717 config :my_app, my_app_databases: [Databases.RepoOne, Databases.RepoTwo] ``` -------------------------------- ### String.slice/3 with negative start Source: https://elixir.hexdocs.pm/String.html Examples of String.slice/3 with negative start positions. The start is normalized against the string length and clamped to 0. ```elixir iex> String.slice("elixir", -4, 4) "ixir" iex> String.slice("elixir", -10, 3) "eli" ``` -------------------------------- ### iodata_length/1 example Source: https://elixir.hexdocs.pm/IO.html Example showing how to get the length of IO data using iodata_length/1. ```elixir iex> IO.iodata_length([1, 2 | <<3, 4>>]) 4 ``` -------------------------------- ### Start an application with Application.start/1 Source: https://elixir.hexdocs.pm/Application.html Starts the application :ex_unit, returning :ok. Starting automatically loads the application if not already loaded and checks that dependencies are started. ```elixir Application.start(:ex_unit) #=> :ok ``` -------------------------------- ### Enum.drop_while/2 example Source: https://elixir.hexdocs.pm/Enum.md Example showing Enum.drop_while/2 dropping elements less than 3 from the start of the list. ```elixir iex> Enum.drop_while([1, 2, 3, 2, 1], fn x -> x < 3 end) [3, 2, 1] ``` -------------------------------- ### Port.open example with cat command Source: https://elixir.hexdocs.pm/Port.md Example showing how to open a port to spawn the 'cat' program, send data, receive responses, and close the port. Demonstrates message passing and the use of the :binary option. ```elixir iex> port = Port.open({:spawn, "cat"}, [:binary]) iex> send(port, {self(), {:command, "hello"}}) iex> send(port, {self(), {:command, "world"}}) iex> flush() {#Port<0.1444>, {:data, "hello"}} {#Port<0.1444>, {:data, "world"}} iex> send(port, {self(), :close}) :ok iex> flush() {#Port<0.1444>, :closed} :ok ``` -------------------------------- ### utc_now/0 examples Source: https://elixir.hexdocs.pm/NaiveDateTime.md Examples of getting the current naive datetime in UTC, with and without truncation to seconds. ```elixir iex> naive_datetime = NaiveDateTime.utc_now() iex> naive_datetime.year >= 2016 true ``` ```elixir iex> naive_datetime = NaiveDateTime.utc_now(:second) iex> naive_datetime.microsecond {0, 0} ``` -------------------------------- ### File.mkdir_p!/1 examples Source: https://elixir.hexdocs.pm/File.html Examples showing successful creation and a raised File.Error when the directory cannot be created. ```elixir File.mkdir_p!("non/existing/parents") #=> :ok File.mkdir_p!("/usr/sbin/temp") ** (File.Error) could not make directory (with -p) "/usr/sbin/temp": not owner ``` -------------------------------- ### init/2 example Source: https://elixir.hexdocs.pm/Supervisor.html Example of using Supervisor.init/2 in a module-based supervisor's init/1 callback with a single child and :one_for_one strategy. ```elixir def init(_init_arg) do children = [ {Counter, 0} ] Supervisor.init(children, strategy: :one_for_one) end ``` -------------------------------- ### NaiveDateTime.local_now/1 example Source: https://elixir.hexdocs.pm/NaiveDateTime.html Example of using local_now/1 to get the current local time and checking its year. ```elixir iex> naive_datetime = NaiveDateTime.local_now() iex> naive_datetime.year >= 2019 true ``` -------------------------------- ### binary_slice/3 examples: basic slicing, negative start, zero size, and out-of-range start Source: https://elixir.hexdocs.pm/Kernel.html These iex examples demonstrate binary_slice/3 behavior: basic slicing with clipping when start+size exceeds the binary size, negative start normalization and clamping, zero size returning an empty binary, and start beyond the binary size returning an empty binary. ```elixir iex> binary_slice("elixir", 0, 6) "elixir" iex> binary_slice("elixir", 0, 5) "elixi" iex> binary_slice("elixir", 1, 4) "lixi" iex> binary_slice("elixir", 0, 10) "elixir" ``` ```elixir iex> binary_slice("elixir", -3, 10) "xir" iex> binary_slice("elixir", -10, 10) "elixir" ``` ```elixir iex> binary_slice("elixir", 1, 0) "" ``` ```elixir iex> binary_slice("elixir", 10, 10) "" ``` -------------------------------- ### Enum.reduce/3 examples Source: https://elixir.hexdocs.pm/Enum.md Examples of using Enum.reduce/3 with a list and a map. The first example sums a list starting from 0; the second sums the values of a map. ```elixir iex> Enum.reduce([1, 2, 3], 0, fn x, acc -> x + acc end) 6 ``` ```elixir iex> Enum.reduce(%{a: 2, b: 3, c: 4}, 0, fn {_key, val}, acc -> acc + val end) 9 ``` -------------------------------- ### format/2 example Source: https://elixir.hexdocs.pm/Inspect.Algebra.html Example showing how to format a document with a width of 30 and 10, producing "hello world" and "hello\nworld" respectively. ```elixir iex> doc = Inspect.Algebra.glue("hello", " ", "world") iex> doc = Inspect.Algebra.group(doc) iex> doc |> Inspect.Algebra.format(30) |> IO.iodata_to_binary() "hello world" iex> doc |> Inspect.Algebra.format(10) |> IO.iodata_to_binary() "hello\nworld" ``` -------------------------------- ### with_index with offset example Source: https://elixir.hexdocs.pm/Stream.md Example showing Stream.with_index/2 with an integer offset, starting indexing from the given offset. ```elixir iex> stream = Stream.with_index([1, 2, 3], 3) iex> Enum.to_list(stream) [{1, 3}, {2, 4}, {3, 5}] ``` -------------------------------- ### Start DynamicSupervisor and add child Source: https://elixir.hexdocs.pm/dynamic-supervisor.md Demonstrates starting a DynamicSupervisor with strategy :one_for_one and adding a child process (KV.Bucket) using DynamicSupervisor.start_child. Shows basic usage in IEx. ```elixir iex> {:ok, sup_pid} = DynamicSupervisor.start_link(strategy: :one_for_one) iex> DynamicSupervisor.start_child(sup_pid, {KV.Bucket, name: :another_list}) iex> KV.Bucket.put(:another_list, "milk", 1) :ok iex> KV.Bucket.get(:another_list, "milk") 1 ``` -------------------------------- ### Macro.Env.expand_alias/4 error example Source: https://elixir.hexdocs.pm/Macro.Env.html Interactive example showing that :error is returned when there is no alias or the alias starts with Elixir. ```elixir iex> alias List, as: MyList iex> Macro.Env.expand_alias(__ENV__, [], [:Elixir, MyList]) :error iex> Macro.Env.expand_alias(__ENV__, [], [:AnotherList]) :error ``` -------------------------------- ### Start an application manually with Application.ensure_all_started/1 Source: https://elixir.hexdocs.pm/Application.html Starts an application and all its dependencies. Returns {:ok, pid} or {:ok, pid, state} on success. ```elixir {:ok, _} = Application.ensure_all_started(:some_app) ``` -------------------------------- ### System.build_info/0 example output Source: https://elixir.hexdocs.pm/System.md Example output of System.build_info/0 in an IEx session, showing the returned map with build, date, otp_release, revision, and version fields. ```elixir iex> System.build_info() %{ build: "1.9.0-dev (772a00a0c) (compiled with Erlang/OTP 21)", date: "2018-12-24T01:09:21Z", otp_release: "21", revision: "772a00a0c", version: "1.9.0-dev" } ``` -------------------------------- ### spawn/3 examples with :monitor and :link options Source: https://elixir.hexdocs.pm/Process.md Examples of Process.spawn/3 with :monitor and :link options. The :monitor option returns a tuple with PID and reference, while :link returns just the PID. ```elixir Process.spawn(fn -> 1 + 2 end, [:monitor]) #=> {#PID<0.93.0>, #Reference<0.18808174.1939079169.202418>} Process.spawn(fn -> 1 + 2 end, [:link]) #=> #PID<0.95.0> ``` -------------------------------- ### module_info/1 example with URI Source: https://elixir.hexdocs.pm/Module.html Example showing how to use module_info/1 to get the module itself and check if a function is exported. ```elixir iex> URI.module_info(:module) URI iex> {:decode_www_form, 1} in URI.module_info(:exports) true ``` -------------------------------- ### lstat examples Source: https://elixir.hexdocs.pm/File.md Examples of using File.lstat to get file information, showing symlink and error cases. ```elixir File.lstat("link_to_hello") #=> {:ok, %File.Stat{type: :symlink, ...}} ``` ```elixir File.lstat("non_existing.txt", time: :posix) #=> {:error, :enoent} ``` -------------------------------- ### Examples for Access.get/3 Source: https://elixir.hexdocs.pm/Access.html IEx session examples demonstrating Access.get/3 with maps and keyword lists, including default values. ```elixir iex> Access.get(%{name: "john"}, :name, "default name") "john" iex> Access.get(%{name: "john"}, :age, 25) 25 iex> Access.get([ordered: true], :timeout) nil ``` -------------------------------- ### get/3 examples Source: https://elixir.hexdocs.pm/Keyword.html IEx examples for get/3, demonstrating retrieval of existing and missing keys, default values, and behavior with duplicate keys. ```elixir iex> Keyword.get([], :a) nil iex> Keyword.get([a: 1], :a) 1 iex> Keyword.get([a: 1], :b) nil iex> Keyword.get([a: 1], :b, 3) 3 ``` ```elixir iex> Keyword.get([a: 1, a: 2], :a, 3) 1 iex> Keyword.get([a: 1, a: 2], :b, 3) 3 ``` -------------------------------- ### NaiveDateTime.utc_now/1 examples Source: https://elixir.hexdocs.pm/NaiveDateTime.html Examples of getting the current UTC naive datetime and truncating it to seconds. The second example shows that the microsecond field becomes {0, 0}. ```elixir iex> naive_datetime = NaiveDateTime.utc_now() iex> naive_datetime.year >= 2016 true iex> naive_datetime = NaiveDateTime.utc_now(:second) iex> naive_datetime.microsecond {0, 0} ``` -------------------------------- ### Code.require_file/2 example - first require Source: https://elixir.hexdocs.pm/Code.html Example showing that when the file has not been required, Code.require_file/2 returns a list of modules. The example uses List.first/1 to get the first module. ```elixir modules = Code.require_file("eex_test.exs", "../eex/test") List.first(modules) #=> {EExTest.Compiled, <<70, 79, 82, 49, ...>>} ``` -------------------------------- ### Start PartitionSupervisor with DynamicSupervisor Source: https://elixir.hexdocs.pm/DynamicSupervisor.html Shows how to start a PartitionSupervisor that will start a DynamicSupervisor for each core. ```elixir children = [ {PartitionSupervisor, child_spec: DynamicSupervisor, name: MyApp.DynamicSupervisors} ] ``` -------------------------------- ### append_path/2 examples Source: https://elixir.hexdocs.pm/URI.html Examples of using URI.append_path/2, including a successful case and an error case when the path does not start with a slash. ```elixir iex> URI.append_path(URI.parse("http://example.com/foo/?x=1"), "/my-path") |> URI.to_string() "http://example.com/foo/my-path?x=1" ``` ```elixir iex> URI.append_path(URI.parse("http://example.com"), "my-path") ** (ArgumentError) path must start with "/", got: "my-path" ``` -------------------------------- ### System.cmd/3 basic example Source: https://elixir.hexdocs.pm/System.md Runs the echo command with the argument "hello" and returns the output and exit status. ```elixir iex> System.cmd("echo", ["hello"]) {"hello\n", 0} ``` -------------------------------- ### String.slice/3 with start beyond length Source: https://elixir.hexdocs.pm/String.html Example showing that when start is greater than the string length, an empty string is returned. ```elixir iex> String.slice("elixir", 10, 1500) "" ``` -------------------------------- ### init/1 example Source: https://elixir.hexdocs.pm/DynamicSupervisor.html Example of using DynamicSupervisor.init/1 in a module-based supervisor's init/1 callback, setting max_children to 1000. ```elixir def init(_arg) do DynamicSupervisor.init(max_children: 1000) end ``` -------------------------------- ### File.open/2 example Source: https://elixir.hexdocs.pm/File.html Example showing how to open a gzip-compressed file for reading and read a line. ```elixir {:ok, file} = File.open("foo.tar.gz", [:read, :compressed]) IO.read(file, :line) File.close(file) ``` -------------------------------- ### get_and_update_in/2 macro example Source: https://elixir.hexdocs.pm/Kernel.html Example of using get_and_update_in/2 with a bracket path to get and update a nested value in a map. ```elixir get_and_update_in(opts[:foo][:bar], &{&1, &1 + 1}) ``` -------------------------------- ### elem/3 examples Source: https://elixir.hexdocs.pm/Kernel.html Examples of using elem/3 to get elements from a tuple, including error cases for invalid indices. ```elixir iex> tuple = {:foo, :bar, 3} iex> elem(tuple, 1) :bar elem({}, 0) ** (ArgumentError) argument error elem({:foo, :bar}, 2) ** (ArgumentError) argument error ``` -------------------------------- ### Example of reading configuration with get_env/3 Source: https://elixir.hexdocs.pm/Application.html Example showing how to retrieve a database configuration using Application.get_env/3 and access the :ip key. ```elixir config = Application.get_env(:my_app, Databases.RepoOne) config[:ip] ``` -------------------------------- ### start_link/1 Source: https://elixir.hexdocs.pm/PartitionSupervisor.html Starts a partition supervisor with the given options. ```APIDOC ## start_link(opts) ### Description Starts a partition supervisor with the given options. ### Function start_link(opts) ### Parameters - **opts** (start_link_option()) - The options to start the supervisor. ### Returns {:ok, pid} or {:error, reason}. ``` -------------------------------- ### Function.info/2 examples with named function Source: https://elixir.hexdocs.pm/Function.md Examples of using Function.info/2 with a named function to get :name and :pid information. ```elixir iex> fun = &String.length/1 iex> Function.info(fun, :name) {:name, :length} iex> Function.info(fun, :pid) {:pid, :undefined} ``` -------------------------------- ### Function.info/2 examples with anonymous function Source: https://elixir.hexdocs.pm/Function.md Examples of using Function.info/2 with an anonymous function to get :arity and :type information. ```elixir iex> f = fn x -> x end iex> Function.info(f, :arity) {:arity, 1} iex> Function.info(f, :type) {:type, :local} ``` -------------------------------- ### KV module with DynamicSupervisor and Registry Source: https://elixir.hexdocs.pm/dynamic-supervisor.md Complete module example showing how to start a DynamicSupervisor in the application supervision tree, create buckets dynamically, and look them up using a Registry. ```elixir defmodule KV do use Application @impl true def start(_type, _args) do children = [ {Registry, name: KV, keys: :unique}, {DynamicSupervisor, name: KV.BucketSupervisor, strategy: :one_for_one} ] Supervisor.start_link(children, strategy: :one_for_one) end @doc """ Creates a bucket with the given name. """ def create_bucket(name) do DynamicSupervisor.start_child(KV.BucketSupervisor, {KV.Bucket, name: via(name)}) end @doc """ Looks up the given bucket. """ def lookup_bucket(name) do GenServer.whereis(via(name)) end defp via(name), do: {:via, Registry, {KV, name}} end ``` -------------------------------- ### fetch/2 examples Source: https://elixir.hexdocs.pm/Access.html Examples showing Access.fetch/2 returning {:ok, "meg"} for an existing key and :error for a missing key. ```elixir iex> Access.fetch(%{name: "meg", age: 26}, :name) {:ok, "meg"} iex> Access.fetch([ordered: true, on_timeout: :exit], :timeout) :error ``` -------------------------------- ### File.mkdir_p/1 examples Source: https://elixir.hexdocs.pm/File.html Examples showing successful creation of nested directories and a failure due to permissions (eperm). ```elixir File.mkdir_p("non/existing/parents") #=> :ok File.mkdir_p("/usr/sbin/temp") #=> {:error, :eperm} ``` -------------------------------- ### System.restart/0 example Source: https://elixir.hexdocs.pm/System.html Example call to System.restart/0, which smoothly takes down all applications, unloads code, closes ports, and starts all applications again. ```elixir System.restart() ``` -------------------------------- ### Start release node with NODES, PORT, and RELEASE_NODE Source: https://elixir.hexdocs.pm/releases.html Starts the release with the node name 'foo' and port 4040. Requires adjusting @computer-name to the actual computer name. ```shell $ NODES="foo@computer-name,bar@computer-name" PORT=4040 RELEASE_NODE="foo" bin/kv start_iex ``` ```shell $ NODES="foo@computer-name,bar@computer-name" PORT=4041 RELEASE_NODE="bar" bin/kv start_iex ``` -------------------------------- ### overridables_in/1 example Source: https://elixir.hexdocs.pm/Module.html Example showing how to use Module.overridables_in/1 to get sorted overridable definitions. The module must not be compiled yet. ```elixir defmodule Example do def foo, do: 1 def bar, do: 2 defoverridable foo: 0, bar: 0 def foo, do: 3 [bar: 0, foo: 0] = Module.overridables_in(__MODULE__) |> Enum.sort() end ``` -------------------------------- ### mkdir examples Source: https://elixir.hexdocs.pm/File.md Examples showing mkdir returning :ok for a successful creation and {:error, :enoent} when a parent directory is missing. ```elixir File.mkdir("test/unit") #=> :ok ``` ```elixir File.mkdir("non/existing") #=> {:error, :enoent} ``` -------------------------------- ### URI.parse/1 protocol-relative URL example Source: https://elixir.hexdocs.pm/URI.html Example of URI.parse/1 with a protocol-relative URL (starting with //), showing scheme nil and port nil. ```elixir iex> URI.parse("//elixir-lang.org/") %URI{ authority: "elixir-lang.org", fragment: nil, host: "elixir-lang.org", path: "/", port: nil, query: nil, scheme: nil, userinfo: nil } ``` -------------------------------- ### Example command sequence and output Source: https://elixir.hexdocs.pm/docs-tests-and-with.html Shows the expected interaction with the server: commands like CREATE, PUT, GET, DELETE and their responses. Used as the specification for the parser to implement. ```text CREATE shopping OK PUT shopping milk 1 OK PUT shopping eggs 3 OK GET shopping milk 1 OK DELETE shopping eggs OK ```