View Source Bunch.Typespec (Bunch v1.6.1)
A bunch of typespec-related helpers.
Summary
Functions
This macro is deprecated. Use Bunch.Typespec.enum_to_alternative/1
instead.
Converts an enumerable of terms to AST of alternative type of these terms.
Functions
This macro is deprecated. Use Bunch.Typespec.enum_to_alternative/1
instead.
Allows to define a type in form of t :: x | y | z | ...
and a module parameter
in form of @t [x, y, z, ...]
at once.
Example
defmodule Abc do
use Bunch.Typespec
@list_type t :: [:a, :b, :c]
@spec get_at(0..2) :: t
def get_at(x), do: @t |> Enum.at(x)
end
Abc.get_at(1) # -> :b
@spec enum_to_alternative(Enumerable.t()) :: Macro.t()
Converts an enumerable of terms to AST of alternative type of these terms.
Useful for defining a type out of a list of constants.
Examples
iex> defmodule Example do
...> @values [1, :a, {true, 3 * 4}]
...> @type value :: unquote(Bunch.Typespec.enum_to_alternative(@values))
...> @spec get_value(0..2) :: value
...> def get_value(i), do: Enum.at(@values, i)
...> end
iex> Example.get_value(1)
:a
iex> Bunch.Typespec.enum_to_alternative([1, :a, {true, 3 * 4}])
quote do
1 | :a | {true, 12}
end