Skip to content

Instantly share code, notes, and snippets.

@trbngr
Last active December 2, 2019 02:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trbngr/22d1103465f7e4c7d6e37b914d7a4dbf to your computer and use it in GitHub Desktop.
Save trbngr/22d1103465f7e4c7d6e37b914d7a4dbf to your computer and use it in GitHub Desktop.
Beging the Ord protocol
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
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