Last active
December 2, 2019 02:28
-
-
Save trbngr/22d1103465f7e4c7d6e37b914d7a4dbf to your computer and use it in GitHub Desktop.
Beging the Ord protocol
This file contains 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
defprotocol Ord do | |
@doc """ | |
iex> Ord.compare("a", "b") | |
:EQ | |
iex> Ord.compare("a", "b", type: :alphabetical) | |
:LT | |
""" | |
def compare(a, b, opts \\ []) | |
def lt(a, b) | |
def lte(a, b) | |
def gt(a, b) | |
def gte(a, b) | |
def max(a, b) | |
def min(a, b) | |
end | |
defimpl Ord, for: BitString do | |
def compare(a, b, opts) do | |
case Keyword.get(opts, :type, :length) do | |
:alphabetical -> string_compare_alphabetical_order(a, b) | |
_ -> string_compare_length(a, b) | |
end | |
end | |
defp string_compare_length(a, b) do | |
cond do | |
String.length(a) < String.length(b) -> :LT | |
String.length(a) == String.length(b) -> :EQ | |
true -> :GT | |
end | |
end | |
defp string_compare_alphabetical_order(a, b) do | |
cond do | |
a < b -> :LT | |
a == b -> :EQ | |
true -> :GT | |
end | |
end | |
end |
This file contains 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 OrdTest do | |
use ExUnit.Case | |
doctest Ord | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment