summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSandy Maguire <sandy@sandymaguire.me>2020-08-14 20:22:31 -0700
committerMarge Bot <ben+marge-bot@smart-cactus.org>2020-09-12 00:31:36 -0400
commitfc965c0910757410d624229419f36f0829cf73f6 (patch)
tree4e9ca16fe96d7bd47f3573dfda0e5e4c1592456f
parent8a5a91cb67e8c4e2558031c04efccf3c378ba254 (diff)
downloadhaskell-fc965c0910757410d624229419f36f0829cf73f6.tar.gz
Add clamp function to Data.Ord
-rw-r--r--libraries/base/Data/Ord.hs16
1 files changed, 16 insertions, 0 deletions
diff --git a/libraries/base/Data/Ord.hs b/libraries/base/Data/Ord.hs
index 8703c7bdc0..9815259dec 100644
--- a/libraries/base/Data/Ord.hs
+++ b/libraries/base/Data/Ord.hs
@@ -21,6 +21,7 @@ module Data.Ord (
Ordering(..),
Down(..),
comparing,
+ clamp,
) where
import Data.Bits (Bits, FiniteBits)
@@ -44,6 +45,21 @@ import GHC.Show
comparing :: (Ord a) => (b -> a) -> b -> b -> Ordering
comparing p x y = compare (p x) (p y)
+-- |
+-- > clamp (low, high) a = min high (max a low)
+--
+-- Function for ensursing the value @a@ is within the inclusive bounds given by
+-- @low@ and @high@. If it is, @a@ is returned unchanged. The result
+-- is otherwise @low@ if @a <= low@, or @high@ if @high <= a@.
+--
+-- >>> clamp (0, 10) 2
+-- 2
+--
+-- >>> clamp ('a', 'm') 'x'
+-- 'm'
+clamp :: (Ord a) => (a, a) -> a -> a
+clamp (low, high) a = min high (max a low)
+
-- | The 'Down' type allows you to reverse sort order conveniently. A value of type
-- @'Down' a@ contains a value of type @a@ (represented as @'Down' a@).
-- If @a@ has an @'Ord'@ instance associated with it then comparing two