packages feed

papa-0.7.0: src/Papa/Lens/Data/List.hs

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

{- HLINT ignore "Avoid restricted function" -}
-- Reason: this module defines Papa's total (!!) (to a Maybe), whose name
-- HLint restricts whatever module it comes from.

-- | Total indexing of any 'Ixed' container.
module Papa.Lens.Data.List (
  (!!),
) where

import Control.Lens (Index, IxValue, Ixed (ix), (^?))
import Data.Maybe (Maybe)

-- $setup
-- >>> :set -XNoImplicitPrelude
-- >>> import Papa
-- >>> import Hedgehog
-- >>> 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))

-- | The element at an index of any 'Ixed' container. 'Data.Maybe.Nothing' for an
-- index that is not there.
--
-- ==== __Examples__
--
-- >>> [10, 20, 30 :: Int] !! (1 :: Int)
-- Just 20
--
-- >>> ([] :: [Int]) !! (0 :: Int)
-- Nothing
--
-- >>> (1 :| [2, 3 :: Int]) !! (2 :: Int)
-- Just 3
--
-- >>> check $ withTests 100 $ property $ do xs <- forAll genInts; i <- forAll (Gen.int (Range.linear (-5) 25)); (xs !! i) === (xs !? i)
-- ...passed 100 tests.
-- True
--
-- @since 0.4.0
(!!) :: (Ixed s) => s -> Index s -> Maybe (IxValue s)
q !! n =
  q ^? ix n
{-# INLINE (!!) #-}

infixl 9 !!