diff options
author | Anselm Schüler <mail@anselmschueler.com> | 2022-06-24 21:39:38 +0200 |
---|---|---|
committer | Anselm Schüler <mail@anselmschueler.com> | 2022-07-04 05:06:42 +0000 |
commit | 36fba0dfa2ecbd27b575dea09e4c3cdd6cb99b37 (patch) | |
tree | 5c0394cf93a2d5c505c1d003ab411f7bd87b4baf /libraries/base | |
parent | 2635c6f2bfb3d1126fa868768fc4b8349d0b9950 (diff) | |
download | haskell-36fba0dfa2ecbd27b575dea09e4c3cdd6cb99b37.tar.gz |
Add applyWhen to Data.Function per CLC prop
Approved by CLC in https://github.com/haskell/core-libraries-committee/issues/71#issuecomment-1165830233
Diffstat (limited to 'libraries/base')
-rw-r--r-- | libraries/base/Data/Function.hs | 29 | ||||
-rw-r--r-- | libraries/base/changelog.md | 1 |
2 files changed, 30 insertions, 0 deletions
diff --git a/libraries/base/Data/Function.hs b/libraries/base/Data/Function.hs index 2947fd58d1..ce4a10961a 100644 --- a/libraries/base/Data/Function.hs +++ b/libraries/base/Data/Function.hs @@ -25,9 +25,11 @@ module Data.Function , (&) , fix , on + , applyWhen ) where import GHC.Base ( ($), (.), id, const, flip ) +import Data.Bool ( Bool(..) ) infixl 0 `on` infixl 1 & @@ -121,5 +123,32 @@ on :: (b -> b -> c) -> (a -> b) -> a -> a -> c (&) :: a -> (a -> b) -> b x & f = f x +-- | 'applyWhen' applies a function to a value if a condition is true, +-- otherwise, it returns the value unchanged. +-- +-- It is equivalent to @'flip' ('Data.Bool.bool' 'id')@. +-- +-- Algebraic properties: +-- +-- * @applyWhen 'True' = 'id'@ +-- +-- * @applyWhen 'False' f = 'id'@ +-- +-- @since 4.18.0.0 +applyWhen :: Bool -> (a -> a) -> a -> a +applyWhen True f x = f x +applyWhen False _ x = x +-- Proofs: +-- +-- flip bool id = \q f -> bool id f q +-- = \f q -> case q of +-- True -> f = \x -> f x +-- False -> id = \x -> x ∎ +-- +-- applyWhen True = \f x -> f x +-- = \f -> \x -> f x = \f -> f = id ∎ +-- +-- applyWhen False f = \x -> x = id ∎ + -- $setup -- >>> import Prelude diff --git a/libraries/base/changelog.md b/libraries/base/changelog.md index 1517a48572..abac4c46d1 100644 --- a/libraries/base/changelog.md +++ b/libraries/base/changelog.md @@ -8,6 +8,7 @@ override the above-mentioned handler. * `Numeric.Natural` re-exports `GHC.Natural.minusNaturalMaybe`. * Add `Data.Foldable1` and `Data.Bifoldable1`. + * Add `applyWhen` to `Data.Function`. ## 4.17.0.0 *TBA* |