tagged v0.4.2 Tagged View Source
Generates definitions to assist working with tagged value tuples,
such as the ubiquitous {:ok, value} and {:error, reason}.
Examples
defmodule Status
use Tagged
deftagged ok(value :: term())
deftagged error(reason :: term())
endConstruct and Destructure
iex> require Status
iex> Status.ok(:computer)
{:ok, :computer}
iex> with Status.error(reason) <- {:ok, :computer}, do: raise reason
{:ok, :computer}See Tagged.Constructor for further details.
Type definitions
_iex> t Status.error
@type error() :: {:error, reason :: term()}
Tagged value tuple, containing reason :: term()See Tagged.Typedef for further details.
Pipe selective execution
iex> require Status
iex> import Status, only: [ok: 1, with_ok: 2]
iex> ok(:computer) |> with_ok(& "OK, #{&1}")
"OK, computer"See Tagged.PipeWith for further details.
Sum Algebraic Data Type: Binary Tree
A module that defines some tagged values, a composit type, and guard of those, forms a Sum Algebraic Data Type, also known as a Tagged Union.
defmodule BinTree do
use Tagged
deftagged tree(left :: t(), right :: t())
deftagged leaf(value :: term())
deftagged nil, as: empty()
@type t() :: tree() | leaf() | empty()
defguard is_t(x) when is_tree(x) or is_leaf(x) or is_empty(x)
@spec leaves(tree()) :: [term()]
def leaves(empty()), do: []
def leaves(leaf(v)), do: [v]
def leaves(tree(l, r)), do: leaves(l) ++ leaves(r)
end
iex> require BinTree
iex> import BinTree
iex> t = tree(leaf(1),
...> tree(leaf(2),
...> empty()))
{:tree, {:leaf, 1}, {:tree, {:leaf, 2}, nil}}
iex> is_t(t)
true
iex> leaves(t)
[1, 2] Link to this section Summary
Link to this section Functions
Defines a public tagged value tuple.
By default the tagged tuple has the same name as the tag, and all of constructor, guard, pipe selector, and type are generated.
If tag is specified bare, as in deftagged ok, the constructor will have an
arity of 1, and the type will wrap a term(), for backwards compatibility.
deftagged ok <=> deftagged ok(term())If the tag is specified in the form of a parameterized type, the
constructor will have the same arity as the specified type.
When the constructor name is changed with as:, the type declaration belongs
to the name, and not the tag.
deftagged ok, as: success(term())Keywords
as: name(...)Override default macro name. See
Tagged.Constructor.type: falseOverride generation of type definition. See
Tagged.Typedef.guard: falseOverride generation of guard expression macros. See
Tagged.Guard.pipe_with: falseOverride generation of pipe filter. See
Tagged.PipeWith.DEPRECATED ~> 0.4.0of: typedefDeclare the wrapped type statically, making it opaque. SeeTagged.Typedef.
Defines a private tagged value tuple.
See Tagged.deftagged/2 for further details and examples.