packages feed

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

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

-- | Total division.
--
-- "Prelude"'s @(/)@, @recip@ and @(^^)@ throw @Ratio has zero denominator@ at
-- 'Data.Ratio.Rational' (and any 'Data.Ratio.Ratio') when they divide by
-- zero. They are in "Papa.Unsafe.Numeric". The functions here take a 'NonZero'
-- divisor, so they cannot, and return the result itself; build the divisor
-- once with @preview nonZero@.
--
-- @since 0.6.0
module Papa.Base.Data.Fractional (
  divideNonZero,
  recipNonZero,
  powNonZero,
) where

import Papa.Base.Data.Divisor (DivisorLike (divisor))
import Papa.Base.Data.NonZero (NonZero)
import Papa.Lens.Optic (the)
import Prelude (Fractional, Integral)
import qualified Prelude as P

-- $setup
-- >>> :set -XNoImplicitPrelude
-- >>> import Papa
-- >>> import Hedgehog
-- >>> import qualified Hedgehog.Gen as Gen
-- >>> import qualified Hedgehog.Range as Range
-- >>> let genRational = Gen.realFrac_ (Range.linearFracFrom 0 (-100) 100) :: Gen Rational
-- >>> let genNonZero = Gen.just (preview nonZero <$> genRational)

-- | Division by a 'NonZero'. "Prelude"'s @(/)@ is in "Papa.Unsafe.Numeric".
--
-- ==== __Examples__
--
-- >>> fmap (divideNonZero 1) (preview nonZero (4 :: Rational))
-- Just (1 % 4)
--
-- >>> fmap (divideNonZero 1) (preview nonZero (0 :: Double))
-- Nothing
--
-- >>> check $ withTests 200 $ property $ do x <- forAll genRational; y <- forAll genNonZero; divideNonZero x y * the divisor y === x
-- ...passed 200 tests.
-- True
--
-- @since 0.7.0
divideNonZero :: (Fractional a) => a -> NonZero a -> a
divideNonZero x y =
  x P./ the divisor y
{-# INLINE divideNonZero #-}

-- | The reciprocal of a 'NonZero'. "Prelude"'s @recip@ is in "Papa.Unsafe.Numeric".
--
-- ==== __Examples__
--
-- >>> fmap recipNonZero (preview nonZero (4 :: Rational))
-- Just (1 % 4)
--
-- >>> check $ withTests 200 $ property $ do x <- forAll genNonZero; recipNonZero x === divideNonZero 1 x
-- ...passed 200 tests.
-- True
--
-- @since 0.7.0
recipNonZero :: (Fractional a) => NonZero a -> a
recipNonZero x =
  P.recip (the divisor x)
{-# INLINE recipNonZero #-}

-- | Exponentiation of a 'NonZero' by an integral power, which may be
-- negative. For a base that may be zero, use 'Papa.Base.Data.Integral.pow',
-- whose power is a 'Data.Word.Word'. "Prelude"'s @(^^)@ is in
-- "Papa.Unsafe.Numeric".
--
-- ==== __Examples__
--
-- >>> fmap (`powNonZero` (-2 :: Int)) (preview nonZero (2 :: Rational))
-- Just (1 % 4)
--
-- >>> fmap (`powNonZero` (0 :: Int)) (preview nonZero (2 :: Rational))
-- Just (1 % 1)
--
-- >>> check $ withTests 200 $ property $ do x <- forAll genNonZero; e <- forAll (Gen.int (Range.linear 0 5)); powNonZero x (negate e) * powNonZero x e === 1
-- ...passed 200 tests.
-- True
--
-- @since 0.7.0
powNonZero :: (Fractional a, Integral b) => NonZero a -> b -> a
powNonZero x n =
  the divisor x P.^^ n
{-# INLINE powNonZero #-}