packages feed

papa-0.7.0: src/Papa/Base/Data/Traversable.hs

{-# LANGUAGE NoImplicitPrelude #-}
{-# OPTIONS_GHC -Wall #-}

-- | Traversals, with the monadic traversals of "Prelude" generalised to
-- 'Applicative'.
module Papa.Base.Data.Traversable (
  module P,
  mapM,
  forM,
  sequence,
) where

import Control.Applicative (Applicative)
import Data.Traversable as P (
  Traversable (sequenceA, traverse),
  fmapDefault,
  foldMapDefault,
  for,
  mapAccumL,
 )

-- $setup
-- >>> :set -XNoImplicitPrelude
-- >>> import Papa
-- >>> import Hedgehog
-- >>> import Hedgehog.Function (fn, apply)
-- >>> import qualified Hedgehog.Gen as Gen
-- >>> import qualified Hedgehog.Range as Range
-- >>> let genInts = Gen.list (Range.linear 0 20) (Gen.int (Range.linear (-100) 100))
-- >>> let genF = fn (Gen.maybe (Gen.int (Range.linear 0 9)))

-- | 'traverse', under the name of "Prelude"'s @mapM@, which needs only
-- 'Applicative'.
--
-- ==== __Examples__
--
-- >>> mapM (\x -> Just (x + 1)) [1, 2, 3 :: Int]
-- Just [2,3,4]
--
-- >>> check $ withTests 100 $ property $ do xs <- forAll genInts; f <- forAll genF; mapM (apply f) xs === traverse (apply f) xs
-- ...passed 100 tests.
-- True
--
-- @since 0.1.0
mapM :: (Traversable t, Applicative f) => (a -> f b) -> t a -> f (t b)
mapM =
  traverse
{-# INLINE mapM #-}

-- | 'for', under the name of "Prelude"'s @forM@, which needs only
-- 'Applicative'.
--
-- ==== __Examples__
--
-- >>> forM [1, 2, 3 :: Int] (\x -> Just (x + 1))
-- Just [2,3,4]
--
-- >>> check $ withTests 100 $ property $ do xs <- forAll genInts; f <- forAll genF; forM xs (apply f) === traverse (apply f) xs
-- ...passed 100 tests.
-- True
--
-- @since 0.1.0
forM :: (Traversable t, Applicative f) => t a -> (a -> f b) -> f (t b)
forM =
  for
{-# INLINE forM #-}

-- | 'sequenceA', under the name of "Prelude"'s @sequence@, which needs only
-- 'Applicative'.
--
-- ==== __Examples__
--
-- >>> sequence [Just 1, Just (2 :: Int)]
-- Just [1,2]
--
-- >>> sequence [Just 1, Nothing :: Maybe Int]
-- Nothing
--
-- >>> check $ withTests 100 $ property $ do xs <- forAll (Gen.list (Range.linear 0 10) (Gen.maybe (Gen.int (Range.linear 0 9)))); sequence xs === sequenceA xs
-- ...passed 100 tests.
-- True
--
-- @since 0.1.0
sequence :: (Traversable t, Applicative f) => t (f a) -> f (t a)
sequence =
  sequenceA
{-# INLINE sequence #-}