packages feed

papa-0.7.0: src/Papa/Base/Data/Ratio.hs

{-# LANGUAGE NoImplicitPrelude #-}
{-# OPTIONS_GHC -Wall #-}

-- | Rational numbers, with 'ratioNonZero', whose denominator is 'NonZero'.
--
-- Only 'Rational', a ratio of 'Prelude.Integer's, is exported: a ratio of a
-- bounded type such as 'Data.Int.Int' wraps around on overflow and so returns
-- wrong numbers. "Data.Ratio"'s @Ratio@, and its @approxRational@ (an
-- arbitrary number for @NaN@ and the infinities; total:
-- 'Papa.Base.Data.RealFrac.approxRationalMaybe'), are in
-- "Papa.Unsafe.Numeric".
module Papa.Base.Data.Ratio (
  module P,
  ratioNonZero,
) where

import Data.Ratio as P (
  Rational,
  denominator,
  numerator,
 )
import qualified Data.Ratio as R
import Papa.Base.Data.Divisor (DivisorLike (divisor))
import Papa.Base.Data.NonZero (NonZero)
import Papa.Lens.Optic (the)
import Prelude (Integer)

-- $setup
-- >>> :set -XNoImplicitPrelude
-- >>> import Papa
-- >>> import Hedgehog
-- >>> import qualified Hedgehog.Gen as Gen
-- >>> import qualified Hedgehog.Range as Range
-- >>> let genInteger = Gen.integral (Range.linearFrom 0 (-1000) 1000) :: Gen Integer
-- >>> let genNonZero = Gen.just (preview nonZero <$> genInteger)

-- | A ratio of an 'Integer' and a 'NonZero' denominator, reduced to lowest
-- terms. "Data.Ratio"'s @%@, which throws for a zero denominator, is in
-- "Papa.Unsafe.Numeric"; this one cannot be given one.
--
-- ==== __Examples__
--
-- >>> fmap (ratioNonZero 6) (preview nonZero 4)
-- Just (3 % 2)
--
-- >>> check $ withTests 200 $ property $ do n <- forAll genInteger; d <- forAll genNonZero; numerator (ratioNonZero n d) * the divisor d === denominator (ratioNonZero n d) * n
-- ...passed 200 tests.
-- True
--
-- @since 0.7.0
ratioNonZero :: Integer -> NonZero Integer -> Rational
ratioNonZero n d =
  n R.% the divisor d
{-# INLINE ratioNonZero #-}