Last active
August 17, 2019 17:21
-
-
Save nicholasjhenry/6cd85bf6b196182c9a9ce7add34f693e to your computer and use it in GitHub Desktop.
Example of implementing equality
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule EqualityExample do | |
import Kernel, except: [==: 2] | |
defprotocol Eq do | |
def eq?(x, y) | |
end | |
defimpl Eq, for: Integer do | |
def eq?(x, y) when is_integer(y) do | |
IO.inspect("#{x} == #{y}") | |
IO.inspect(Kernel.==(x, y)) | |
end | |
end | |
defmacro __using__(_) do | |
quote do | |
import Kernel, except: [==: 2, +: 2, <: 2] | |
import EqualityExample | |
alias EqualityExample.Eq | |
end | |
end | |
def x == y, do: Eq.eq?(x, y) | |
def x + y, do: add(x, y) | |
def add(x, y) do | |
IO.inspect("#{x} + #{y}") | |
IO.inspect(Kernel.+(x, y)) | |
end | |
end | |
defmodule Context do | |
def test(x) when x == 1 do | |
use EqualityExample | |
1 == 2 | |
1 + (2 + 3) | |
1 == "a" | |
end | |
end | |
Context.test(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment