Operator (Operator v0.2.1) View Source

Helpers for defining operator aliases for functions

Operators can be hard to follow, especially with the limited number available in Elixir. Always having a named function backing an operator makes it easy to fall back to the named version. Named fall backs are also very useful for piping (|>).

Examples

defmodule Example do
  use Operator

  @doc "Divide two numbers"
  @operator :~>
  def divide(a, b), do: a / b

  @doc "Multiply two numbers"
  @operator :<~>
  def multiply(a, b), do: a * b
end

import Example

divide(10, 5)
#=> 5

10 ~> 2
#=> 5

multiply(10, 2)
#=> 20

10 <~> 2
#=> 20

Link to this section Summary

Functions

Modified def that applies the most recent @operator

Define an operator alias for a named function

Workaround for defdelegate with variables in AST

Get the current value of @operator

Unset @operator to prevent operator name collisions

Link to this section Functions

Link to this macro

def(fun_head, expr \\ nil)

View Source (macro)

Modified def that applies the most recent @operator

Examples

# ...
@operator :<~>
# ...
def add(a, b), do: a + b

add(1, 2)
#=> 3

1 <~> 2
#=> 3
Link to this macro

defalias(fun_head, list)

View Source (macro)

Define an operator alias for a named function

Examples

defalias(:max, [], 2, as: :<|>)

10 <|> 8
#=> 10
Link to this macro

dispatch_alias(fun_head, operator_symbol)

View Source (macro)

Workaround for defdelegate with variables in AST

This is an ABSURD workaround. Just brute forcing the problem for now. Need to revisit, obviously. Having difficulty interpolating a ~> b into defdelegate because unquoting tries to fully evaluate what looks like a function call

The hope is that this function will be able to be removed completely, hence isolating it here

Specs

get() :: nil | atom()

Get the current value of @operator

Specs

unset() :: no_return()

Unset @operator to prevent operator name collisions