Needlework (Needlework v1.0.0) View Source

Needlework brings additional operators to Elixir that allows you to "thread" results of your functions into other function calls. Basically extending the Kernel.|>/2 operator.

Just use Needlework in your modules and thread away!

Example:

defmodule MyModule do
use Needlework

  @spec foo(func :: fun()) :: list()
  def foo(func) do
    func
    ~> Enum.map([1, 2, 3])
  end
end

Link to this section Summary

Functions

Bind operator.

Same as Needlework.<|>/2 but places the value instead of _.

Allows to thread the value on the left as the last argument

Allows to thread the value on the left to a specific spot on the right.

Wraps the value in Needlework.ok/0 tuple.

Link to this section Types

Specs

error() :: {:error, any()}

Specs

ok() :: {:ok, any()}

Link to this section Functions

Link to this macro

left <|> right

View Source (macro)

Bind operator.

If value on the left is a plain value -> converts it to Needlework.ok/0 | Needlework.error/0 tuple then desctructures the tuple. If it was Needlework.ok/0 tuple -> passes the value for evaluation. If it was Needlework.ok/0 tuple -> skips the evaluation

Example:

iex> import Needlework
iex> foo = fn x -> {:ok, x * 2} end
iex> 2 <|> foo.() <|> foo.() <|> foo.()
{:ok, 16}
iex> bar = fn _ -> {:error, "impossible"} end
iex> 2 <|> foo.() <|> bar.() <|> foo.()
{:error, "impossible"}
Link to this macro

left <~> right

View Source (macro)

Same as Needlework.<|>/2 but places the value instead of _.

If no _ present works like a Needlework.<|>/2

Examples:

iex> import Needlework
iex> foo = fn x, y -> {:ok, x ++ y} end
iex> [1, 2, 3] <~> foo.(_, [1, 2, 3]) <~> foo.([4, 5, 6], _)
{:ok, [4, 5, 6, 1, 2, 3, 1, 2, 3]}
iex> [1, 2, 3] <~> foo.([1, 2, 3]) <~> foo.([4, 5, 6])
{:ok, [1, 2, 3, 1, 2, 3, 4, 5, 6]}
iex> bar = fn _, _ -> {:error, "reason"} end
iex> [1, 2, 3] <~> bar.([1, 2, 3]) <~> foo.([4, 5, 6])
{:error, "reason"}

Allows to thread the value on the left as the last argument

Example:

iex> import Needlework
iex> [1, 2, 3] ~> Kernel.++([4, 5, 6])
[4, 5, 6, 1, 2, 3]
iex> fn x -> x*2 end ~> Enum.map([1, 2, 3])
[2, 4, 6]
Link to this macro

left ~>> right

View Source (macro)

Allows to thread the value on the left to a specific spot on the right.

Value from the left will be placed instead of _. If no _ present works like a regular Kernel.|>/2

Example:

iex> import Needlework
iex> [1, 2, 3] ~>> Kernel.++([4, 5, 6], _)
[4, 5, 6, 1, 2, 3]
iex> [1, 2, 3] ~>> Kernel.++([4, 5, 6])
iex> [] ~>> Enum.reduce([1, 2, 3], _, fn x, acc -> [x | acc] end)
[3, 2, 1]

Specs

ok_unit(any()) :: {:ok | :error, any()}

Wraps the value in Needlework.ok/0 tuple.

Example:

iex> 5 |> Needlework.ok_unit()
{:ok, 5}
iex> {:ok, 5} |> Needlework.ok_unit()
{:ok, 5}
iex> {:error, ""} |> Needlework.ok_unit()
{:error, ""}