Skip to content

Commit

Permalink
Add abs function. 1.3.0
Browse files Browse the repository at this point in the history
  • Loading branch information
q60 committed Aug 19, 2022
1 parent bb40f52 commit 451d766
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 4 deletions.
10 changes: 7 additions & 3 deletions lib/rational.ex
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ defmodule Rational do
Rational
iex> ~n(2/12)
2.0/12.0
1/6
iex> ~n(1/4) * ~n(2/3)
1/6
Expand All @@ -34,9 +34,9 @@ defmodule Rational do

defmacro __using__(_opts) do
quote do
import Kernel, except: [+: 2, -: 2, *: 2, /: 2, **: 2]
import Kernel, except: [+: 2, -: 2, *: 2, /: 2, **: 2, abs: 1]
import RationalMath
import Rational
import Rational, only: [sigil_n: 2, parse: 1, compare: 2]
end
end

Expand Down Expand Up @@ -115,6 +115,7 @@ defmodule Rational do
end
end

@doc false
@spec op(number(), number(), operator()) :: number()
def op(a, b, op) when is_number(a) and is_number(b) do
{res, _} =
Expand Down Expand Up @@ -188,6 +189,9 @@ defmodule Rational do
|> result()
end

def op(a, :abs) when is_rational(a), do: %Rational{num: abs(a.num), denom: abs(a.denom)}
def op(a, :abs) when is_number(a),do: abs(a)

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

Expand Down
2 changes: 2 additions & 0 deletions lib/rational_math.ex
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ defprotocol RationalMath do
def a * b
def a / b
def a ** b
def abs(a)
end

defimpl RationalMath, for: [Rational, Integer, Float] do
Expand All @@ -16,4 +17,5 @@ defimpl RationalMath, for: [Rational, Integer, Float] do
def a * b, do: Rational.op(a, b, :*)
def a / b, do: Rational.op(a, b, :/)
def a ** b, do: Rational.op(a, b, :**)
def abs(a), do: Rational.op(a, :abs)
end
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.2.0",
version: "1.3.0",
elixir: "~> 1.13",
start_permanent: Mix.env() == :prod,
description: description(),
Expand Down

0 comments on commit 451d766

Please sign in to comment.