From 3abc441b92beff2217c3b88c8dc78ea24acbf704 Mon Sep 17 00:00:00 2001 From: Alexey Kuleshevich Date: Sat, 28 Oct 2023 15:36:01 +0200 Subject: [PATCH] Export helper functions `isInRangeOrd` and `isInRangeEnum` --- CHANGELOG.md | 1 + src/System/Random/Internal.hs | 17 ++++++++++++++++- src/System/Random/Stateful.hs | 2 ++ 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 94dd3213..cd429f5d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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) diff --git a/src/System/Random/Internal.hs b/src/System/Random/Internal.hs index 6455f732..b13aafcc 100644 --- a/src/System/Random/Internal.hs +++ b/src/System/Random/Internal.hs @@ -59,6 +59,8 @@ module System.Random.Internal , uniformFloatPositive01M , uniformEnumM , uniformEnumRM + , isInRangeOrd + , isInRangeEnum -- * Generators for sequences of pseudo-random bytes , genShortByteStringIO @@ -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 @@ -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 #-} diff --git a/src/System/Random/Stateful.hs b/src/System/Random/Stateful.hs index 17e9c830..37a7205d 100644 --- a/src/System/Random/Stateful.hs +++ b/src/System/Random/Stateful.hs @@ -79,6 +79,8 @@ module System.Random.Stateful , uniformListM , uniformViaFiniteM , UniformRange(..) + , isInRangeOrd + , isInRangeEnum -- * Generators for sequences of pseudo-random bytes , genShortByteStringIO