Skip to content
Oeiuwq Faith Blog OpenSource Porfolio

witchcrafters/operator

Helpers for defining Elixir operators

witchcrafters/operator.json
{
"createdAt": "2016-10-17T05:34:55Z",
"defaultBranch": "main",
"description": "Helpers for defining Elixir operators",
"fullName": "witchcrafters/operator",
"homepage": null,
"language": "Elixir",
"name": "operator",
"pushedAt": "2021-11-04T04:22:50Z",
"stargazersCount": 23,
"topics": [
"macros",
"operators"
],
"updatedAt": "2024-07-25T14:02:45Z",
"url": "https://github.com/witchcrafters/operator"
}

Build Status Inline docs Deps Status hex.pm version API Docs license

def deps do
[{:operator, "~> 0.2.0"}]
end
defmodule MyModule do
use Operator
@operator :~>
# ...
end

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 (|>).

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

Elixir has a limited number of available operators. Many of them are already used by Kernel (the standard lib). You can overwrite the standard definition by excluding it from the import of Kernel, but this is not advisable (except in very exceptional cases), because it can be very confusing for users.

Some operators have multiple arities, and can be defined separately. Some binary operators associate to the left, and others to the right. Please refer to the table below.

OperatorUnaryLeft-associated BinaryRight-associated Binary
!:heavy_check_mark:
@:heavy_check_mark:
.:heavy_check_mark:
..:heavy_check_mark:
+:heavy_check_mark::heavy_check_mark:
++:heavy_check_mark:
-:heavy_check_mark::heavy_check_mark:
--:heavy_check_mark:
*:heavy_check_mark:
/:heavy_check_mark:
^:heavy_check_mark:
^^^:heavy_check_mark:
~~~:heavy_check_mark:
&:heavy_check_mark:
&&:heavy_check_mark:
&&&:heavy_check_mark:
<-:heavy_check_mark:
\\:heavy_check_mark:
|:heavy_check_mark:
||:heavy_check_mark:
|||:heavy_check_mark:
=:heavy_check_mark:
=~:heavy_check_mark:
==:heavy_check_mark:
===:heavy_check_mark:
!=:heavy_check_mark:
!==:heavy_check_mark:
<:heavy_check_mark:
>:heavy_check_mark:
<>:heavy_check_mark:
<=:heavy_check_mark:
>=:heavy_check_mark:
|>:heavy_check_mark:
<|>:heavy_check_mark:
<~>:heavy_check_mark:
~>:heavy_check_mark:
~>>:heavy_check_mark:
>>>:heavy_check_mark:
<~:heavy_check_mark:
<<~:heavy_check_mark:
<<<:heavy_check_mark:
when:heavy_check_mark:
in:heavy_check_mark:
and:heavy_check_mark:
or:heavy_check_mark:
not:heavy_check_mark: