Skip to content

Commit

Permalink
Export helper functions isInRangeOrd and isInRangeEnum
Browse files Browse the repository at this point in the history
  • Loading branch information
lehins committed Oct 28, 2023
1 parent 74a0991 commit 3abc441
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# 1.3.0

* Add `isInRangeOrd` and `isInRangeEnum` that can be used for implementing `isInRange`
* Add `isInRange` to `UniformRange`: [#78](https://github.com/haskell/random/pull/78)
* Add default implementation for `uniformRM` using `Generics`:
[#92](https://github.com/haskell/random/pull/92)
Expand Down
17 changes: 16 additions & 1 deletion src/System/Random/Internal.hs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ module System.Random.Internal
, uniformFloatPositive01M
, uniformEnumM
, uniformEnumRM
, isInRangeOrd
, isInRangeEnum

-- * Generators for sequences of pseudo-random bytes
, genShortByteStringIO
Expand Down Expand Up @@ -723,7 +725,9 @@ class UniformRange a where
-- > isInRange (lo, hi) lo' && isInRange (lo, hi) hi' && isInRange (lo', hi') x
-- > ==> isInRange (lo, hi) x
--
-- There is a default implementation of 'isInRange' via 'Generic'.
-- There is a default implementation of 'isInRange' via 'Generic'. Other helper function
-- that can be used for implementing this function are `isInRangeOrd` and
-- `isInRangeEnum`
--
-- @since 1.3.0
isInRange :: (a, a) -> a -> Bool
Expand Down Expand Up @@ -762,9 +766,20 @@ instance (GUniformRange f, GUniformRange g) => GUniformRange (f :*: g) where
gisInRange (x1 :*: y1, x2 :*: y2) (x3 :*: y3) =
gisInRange (x1, x2) x3 && gisInRange (y1, y2) y3

-- | Utilize `Ord` instance to decide if a value is within the range. Designed to be used
-- for implementing `isInRange`
--
-- @since 1.3.0
isInRangeOrd :: Ord a => (a, a) -> a -> Bool
isInRangeOrd (a, b) x = min a b <= x && x <= max a b

-- | Utilize `Enum` instance to decide if a value is within the range. Designed to be used
-- for implementing `isInRange`
--
-- @since 1.3.0
isInRangeEnum :: Enum a => (a, a) -> a -> Bool
isInRangeEnum (a, b) x = isInRangeOrd (fromEnum a, fromEnum b) (fromEnum x)

instance UniformRange Integer where
uniformRM = uniformIntegralM
{-# INLINE uniformRM #-}
Expand Down
2 changes: 2 additions & 0 deletions src/System/Random/Stateful.hs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,8 @@ module System.Random.Stateful
, uniformListM
, uniformViaFiniteM
, UniformRange(..)
, isInRangeOrd
, isInRangeEnum

-- * Generators for sequences of pseudo-random bytes
, genShortByteStringIO
Expand Down

0 comments on commit 3abc441

Please sign in to comment.