papa-0.7.0: src/Papa/Base/Control/Applicative.hs
{-# LANGUAGE NoImplicitPrelude #-}
{-# OPTIONS_GHC -Wall #-}
-- | Applicative functors, with 'const' generalised to any 'Applicative'.
module Papa.Base.Control.Applicative (
Applicative (pure, (<*>), (*>), (<*)),
Alternative (empty, (<|>), some, many),
Const (Const, getConst),
WrappedMonad (WrapMonad, unwrapMonad),
WrappedArrow (WrapArrow, unwrapArrow),
ZipList (ZipList, getZipList),
(<$>),
(<$),
(<**>),
liftA,
liftA2,
liftA3,
optional,
const,
replicateA,
replicateA_,
) where
import Control.Applicative (
Alternative (empty, many, some, (<|>)),
Applicative (pure, (*>), (<*), (<*>)),
Const (Const, getConst),
WrappedArrow (WrapArrow, unwrapArrow),
WrappedMonad (WrapMonad, unwrapMonad),
ZipList (ZipList, getZipList),
liftA,
liftA2,
liftA3,
optional,
(<$),
(<$>),
(<**>),
)
import Control.Monad (replicateM, replicateM_)
import Data.Int (Int)
-- $setup
-- >>> :set -XNoImplicitPrelude
-- >>> import Papa
-- >>> import Hedgehog
-- >>> import qualified Hedgehog.Gen as Gen
-- >>> import qualified Hedgehog.Range as Range
-- >>> let genInt = Gen.int (Range.linear (-100) 100)
-- | 'pure', under the name of "Prelude"'s @const@. At the function
-- 'Applicative' (@f = (->) b@) it is "Prelude"'s @const@.
--
-- ==== __Examples__
--
-- >>> const 'a' (1 :: Int)
-- 'a'
--
-- >>> const 'a' :: Maybe Char
-- Just 'a'
--
-- >>> check $ withTests 100 $ property $ do a <- forAll genInt; b <- forAll genInt; const a b === a
-- ...passed 100 tests.
-- True
--
-- @since 0.1.0
const :: (Applicative f) => a -> f a
const =
pure
{-# INLINE const #-}
-- | Perform an action @n@ times, collecting the results. No times for
-- @n <= 0@. This is 'replicateM', which needs only 'Applicative'.
--
-- ==== __Examples__
--
-- >>> replicateA 3 (Just 'x')
-- Just "xxx"
--
-- >>> replicateA 0 (Nothing :: Maybe Char)
-- Just ""
--
-- >>> replicateA 2 "ab"
-- ["aa","ab","ba","bb"]
--
-- >>> check $ withTests 100 $ property $ do n <- forAll (Gen.int (Range.linear (-5) 10)); a <- forAll genInt; replicateA n (Just a) === Just (replicate n a)
-- ...passed 100 tests.
-- True
--
-- @since 0.1.0
replicateA :: (Applicative f) => Int -> f a -> f [a]
replicateA =
replicateM
{-# INLINE replicateA #-}
-- | Perform an action @n@ times, discarding the results. No times for
-- @n <= 0@. This is 'replicateM_', which needs only 'Applicative'.
--
-- ==== __Examples__
--
-- >>> replicateA_ 3 (Just 'x')
-- Just ()
--
-- >>> replicateA_ 2 "ab"
-- [(),(),(),()]
--
-- >>> check $ withTests 100 $ property $ do n <- forAll (Gen.int (Range.linear (-5) 6)); replicateA_ n "ab" === void (replicateA n "ab")
-- ...passed 100 tests.
-- True
--
-- @since 0.1.0
replicateA_ :: (Applicative f) => Int -> f a -> f ()
replicateA_ =
replicateM_
{-# INLINE replicateA_ #-}