coingaming / comparable Goto Github PK
View Code? Open in Web Editor NEWComparable Elixir protocol
Comparable Elixir protocol
defcomparable
works fine for equality/non equality checks, but the way that it executes the same code block on both branches yields incorrect results.
defmacro defcomparable(
{:"::", _, [left_expression, quoted_left_type]},
{:"::", _, [right_expression, quoted_right_type]},
do: code
) do
{left_type, []} = Code.eval_quoted(quoted_left_type, [], __CALLER__)
{right_type, []} = Code.eval_quoted(quoted_right_type, [], __CALLER__)
lr_type =
[Comparable, Type, left_type, To, right_type]
|> Module.concat()
rl_type =
[Comparable, Type, right_type, To, left_type]
|> Module.concat()
lr_impl =
quote do
defmodule unquote(lr_type) do
@fields [:left, :right]
@enforce_keys @fields
defstruct @fields
end
defimpl Comparable, for: unquote(lr_type) do
def compare(%unquote(lr_type){
left: unquote(left_expression),
right: unquote(right_expression)
}) do
unquote(code)
end
end
end
if lr_type == rl_type do
lr_impl
else
quote do
unquote(lr_impl)
defmodule unquote(rl_type) do
@fields [:left, :right]
@enforce_keys @fields
defstruct @fields
end
defimpl Comparable, for: unquote(rl_type) do
def compare(%unquote(rl_type){
left: unquote(right_expression),
right: unquote(left_expression)
}) do
# adding this case statement makes it properly switch the ordering when comparing
case unquote(code) do
:gt -> :lt
:lt -> :gt
:eq -> :eq
end
end
end
end
end
end
I've added a case statement for rl_type
to show what I think it should do.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.