Skip to content

Commit 505620d

Browse files
authored
Merge pull request #12 from anttih/gcd-ratio
Define gcd for Ratio
2 parents c43b63b + 4bd3eb0 commit 505620d

File tree

2 files changed

+16
-10
lines changed

2 files changed

+16
-10
lines changed

src/Data/Ratio.purs

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
1-
module Data.Ratio where
1+
module Data.Ratio
2+
( Ratio(Ratio)
3+
, numerator
4+
, denominator
5+
, gcd
6+
) where
27

38
import Prelude
49

@@ -27,3 +32,9 @@ numerator (Ratio a _) = a
2732

2833
denominator :: forall a. Ratio a -> a
2934
denominator (Ratio _ b) = b
35+
36+
gcd :: forall a. (Eq a, EuclideanRing a) => Ratio a -> a
37+
gcd (Ratio m n)
38+
| n == zero = m
39+
| otherwise = gcd (Ratio n (m `mod` n))
40+

src/Data/Rational.purs

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ module Data.Rational
88

99
import Prelude
1010
import Data.Int as Int
11-
import Data.Ratio (Ratio(Ratio))
11+
import Data.Ratio (Ratio(Ratio), gcd)
1212

1313
newtype Rational = Rational (Ratio Int)
1414

@@ -55,16 +55,11 @@ fromInt :: Int -> Rational
5555
fromInt i = Rational $ Ratio i 1
5656

5757
reduce :: Rational -> Rational
58-
reduce (Rational (Ratio a b)) =
59-
let x = a / gcd a b
60-
y = b / gcd a b
58+
reduce (Rational ratio@(Ratio a b)) =
59+
let x = a / gcd ratio
60+
y = b / gcd ratio
6161
in Rational $ Ratio (x * signum y) (abs y)
6262

63-
gcd :: Int -> Int -> Int
64-
gcd m n
65-
| n == 0 = m
66-
| otherwise = gcd n (m `mod` n)
67-
6863
signum :: Int -> Int
6964
signum 0 = 0
7065
signum x' | x' < 0 = -1

0 commit comments

Comments
 (0)