tagged v0.4.1 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())
end
Construct 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
Functions
Generates a macro that definies all things related to a tagged value tuple,
{atom(), term()}
. By default the macro has the same name as the tag, and all
the things are generated.
Link to this section Functions
Generates a macro that definies all things related to a tagged value tuple,
{atom(), term()}
. By default the macro has the same name as the tag, and all
the things 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: false
Override generation of type definition. See
Tagged.Typedef
.guard: false
Override generation of guard expression macros. See
Tagged.Guard
.pipe_with: false
Override generation of pipe filter. See
Tagged.PipeWith
.DEPRECATED ~> 0.4.0of: typedef
Declare the wrapped type statically, making it opaque. SeeTagged.Typedef
.