Matcha.Spec (Matcha v0.1.3) View Source

About specs.

Link to this section Summary

Functions

Uses a spec to filter out and manipulate elements of an enumerable.

Produces a Stream that filters out and manipulates elements of an enumerable.

Link to this section Types

Specs

t() :: %Matcha.Spec{
  compiled: Matcha.Source.compiled() | nil,
  context: Matcha.Context.t(),
  node: Node.t() | nil,
  source: Matcha.Source.spec()
}

Link to this section Functions

Link to this function

filter_map(spec, enumerable)

View Source

Specs

filter_map(t(), Enumerable.t()) :: list()

Uses a spec to filter out and manipulate elements of an enumerable.

Elements of the enumerable that match one of the spec's clauses will transformed as instructed. Elements that do not match will be filtered out of the result.

Always returns a list.

Examples

iex> require Matcha
...> spec = Matcha.spec do
...>   {amount, tax} when is_integer(amount) and amount > 0 -> {:credit, amount + tax}
...> end
...> Matcha.Spec.filter_map(spec, [
...>   {9001, 0},
...>   {-200, -2.50},
...>   {-3, -0.5},
...>   {:error, "bank was offline"},
...>   {100, 0},
...>   {-743, -16.0},
...> ])
[credit: 9001, credit: 100]

Note

This function converts the enumerable to a list, which will trigger full enumeration of things like lazy Streams. If used with an infinite stream, it will run forever! Consider using stream/2 if you need lazy filter/mapping. It isn't as efficient, but plays nicer with infinite streams, and fits into the Stream APIs.

Specs

Specs

Link to this function

stream(spec, enumerable)

View Source

Specs

stream(t(), Enumerable.t()) :: Enumerable.t()

Produces a Stream that filters out and manipulates elements of an enumerable.

Elements of the enumerable that match one of the spec's clauses will transformed as instructed. Elements that do not match will be filtered out of the result.

Always returns a lazy Stream enumerable.

Examples

iex> require Matcha
...> spec = Matcha.spec do
...>   {amount, tax} when is_integer(amount) and amount < 0 -> {:charge, amount + tax}
...> end
...> Matcha.Spec.stream(spec, [
...>   {9001, 0},
...>   {-200, -2.50},
...>   {-3, -0.5},
...>   {:error, "bank was offline"},
...>   {100, 0},
...>   {-743, -16.0},
...> ])
...> |> Stream.take(2)
...> |> Enum.to_list
[charge: -202.5, charge: -3.5]

Note

This function wraps the enumerable in a lazy Stream. If the enumerable is something you can safely convert to a list without going on forever or loading too much into memory, consider using filter_map/2 instead, as it is much more efficient.

Specs

valid?(t()) :: boolean()

Specs

validate(t()) :: {:ok, t()} | {:error, Matcha.Error.problems()}

Specs

validate!(t()) :: t() | no_return()