packages feed

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

{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# OPTIONS_GHC -Wall #-}

-- | The name @right@ (classy optics, rule 4): the value of the @Right@ side of a
-- sum.
--
-- Its target is a type variable, so the name has no identity instance
-- (rule 4). Its instance for 'Either', a library type, is in this module
-- (rule 15).
--
-- @since 0.7.0
module Papa.Base.Data.Right (
  RightLike (..),
) where

import Control.Lens (Choice, Optic, _Right)
import Data.Either (Either)
import Data.Type.Equality (type (~))
import Prelude (Applicative)

-- $setup
-- >>> :set -XNoImplicitPrelude
-- >>> import Papa
-- >>> import Hedgehog
-- >>> import qualified Hedgehog.Gen as Gen
-- >>> import qualified Hedgehog.Range as Range
-- >>> let genEither = Gen.either (Gen.int (Range.linear 0 9)) Gen.alpha

-- | A field or a constructor named @right@.
--
-- ==== __Examples__
--
-- >>> preview right (Right 'x' :: Either Int Char)
-- Just 'x'
--
-- >>> preview right (Left 1 :: Either Int Char)
-- Nothing
--
-- >>> review right 'x' :: Either Int Char
-- Right 'x'
--
-- Prism laws:
--
-- >>> check $ withTests 100 $ property $ do x <- forAll (Gen.alpha); preview right (review right x :: Either Int Char) === Just x
-- ...passed 100 tests.
-- True
--
-- >>> check $ withTests 100 $ property $ do e <- forAll genEither; for_ (preview right e) (\x -> review right x === e)
-- ...passed 100 tests.
-- True
--
-- @since 0.7.0
class RightLike p f x x' a a' | x -> a where
  right ::
    Optic p f x x' a a'

-- Prism
instance (Choice p, Applicative f, x' ~ Either a b') => RightLike p f (Either a b) x' b b' where
  right =
    _Right
  {-# INLINE right #-}