Skip to content

Commit

Permalink
Add compare function. 1.2.0
Browse files Browse the repository at this point in the history
  • Loading branch information
q60 committed Aug 15, 2022
1 parent 88bdf2c commit bb40f52
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 9 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ qrational is [available in Hex](https://hex.pm/packages/qrational) and can be in
```elixir
def deps do
[
{:rational, "~> 1.1", hex: :qrational}
{:rational, "~> 1.2", hex: :qrational}
]
end
```
Expand Down
33 changes: 26 additions & 7 deletions lib/rational.ex
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ defmodule Rational do
## Some examples
iex> use Rational
Kernel
Rational
iex> ~n(2/12)
2.0/12.0
Expand All @@ -34,9 +34,9 @@ defmodule Rational do

defmacro __using__(_opts) do
quote do
import Rational
import RationalMath
import Kernel, except: [+: 2, -: 2, *: 2, /: 2, **: 2]
import RationalMath
import Rational
end
end

Expand Down Expand Up @@ -96,14 +96,30 @@ defmodule Rational do
@spec sigil_n(String.t(), list()) :: rational()
def sigil_n(string, _modifiers), do: parse(string)

defp gcd(a, 0), do: abs(a)
defp gcd(a, b), do: gcd(b, rem(a, b))
@doc """
Compares two rationals.
Returns `:gt` if first rational is greater than the second and `:lt` for vice versa. If the two rationals are equal `:eq` is returned.
"""
@spec compare(rational(), rational()) :: :lt | :eq | :gt
def compare(a, b) do
case {a.num / a.denom, b.num / b.denom} do
{first, second} when first > second ->
:gt

{first, second} when first < second ->
:lt

_ ->
:eq
end
end

@spec op(number(), number(), operator()) :: number()
def op(a, b, op) when is_number(a) and is_number(b) do
{res, _} =
[a, op, b]
|> Enum.join()
[inspect(a), op, inspect(b)]
|> Enum.join(" ")
|> Code.eval_string()

res
Expand Down Expand Up @@ -172,6 +188,9 @@ defmodule Rational do
|> result()
end

defp gcd(a, 0), do: abs(a)
defp gcd(a, b), do: gcd(b, rem(a, b))

defp result({num, denom}) when num < 0 and denom < 0, do: result({abs(num), abs(denom)})

defp result({num, denom}) do
Expand Down
2 changes: 1 addition & 1 deletion mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ defmodule Rational.MixProject do
def project do
[
app: :rational,
version: "1.1.0",
version: "1.2.0",
elixir: "~> 1.13",
start_permanent: Mix.env() == :prod,
description: description(),
Expand Down

0 comments on commit bb40f52

Please sign in to comment.