Skip to content

Commit

Permalink
Add monomorphic function power.
Browse files Browse the repository at this point in the history
  • Loading branch information
jonathanknowles authored and Anviking committed Apr 7, 2022
1 parent 03dee0b commit 7642fa1
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
14 changes: 14 additions & 0 deletions lib/numeric/src/Cardano/Numeric/Util.hs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ module Cardano.Numeric.Util
-- * Partial orders
, inAscendingPartialOrder

-- * Monomorphic functions
, power

) where

import Prelude hiding
Expand Down Expand Up @@ -301,3 +304,14 @@ round :: (RealFrac a, Integral b) => RoundingDirection -> a -> b
round = \case
RoundUp -> ceiling
RoundDown -> floor

--------------------------------------------------------------------------------
-- Monomorphic functions
--------------------------------------------------------------------------------

-- | Power function where all arguments are of the same type.
--
-- Helps to avoid the use of boilerplate type annotations.
--
power :: Integral a => a -> a -> a
power = (^)
14 changes: 12 additions & 2 deletions lib/numeric/test/unit/Cardano/Numeric/UtilSpec.hs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ module Cardano.Numeric.UtilSpec
import Prelude

import Cardano.Numeric.Util
( equipartitionNatural, padCoalesce, partitionNatural )
( equipartitionNatural, padCoalesce, partitionNatural, power )
import Data.List.NonEmpty
( NonEmpty (..) )
import Data.Maybe
Expand All @@ -20,7 +20,7 @@ import Data.Ratio
import Numeric.Natural
( Natural )
import Test.Hspec
( Spec, describe, it )
( Spec, describe, it, shouldBe )
import Test.QuickCheck
( Arbitrary (..)
, Property
Expand Down Expand Up @@ -70,6 +70,16 @@ spec = do
it "prop_partitionNatural_fair" $
withMaxSuccess 1000 $ checkCoverage prop_partitionNatural_fair

describe "power" $ do

it "equivalent to (^)" $ do
2 `power` 8
`shouldBe` (256 :: Int)
2 `power` 8 - 1
`shouldBe` (255 :: Int)
2 `power` 8 + 1
`shouldBe` (257 :: Int)

--------------------------------------------------------------------------------
-- Coalescing values
--------------------------------------------------------------------------------
Expand Down

1 comment on commit 7642fa1

@whs-dot-hk
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice

Please sign in to comment.