{-# LANGUAGE Rank2Types #-}

-----------------------------------------------------------------------------
-- |
-- Module      :  Data.Typeable.Lens
-- Copyright   :  (C) 2012-16 Edward Kmett
-- License     :  BSD-style (see the file LICENSE)
-- Maintainer  :  Edward Kmett <ekmett@gmail.com>
-- Stability   :  experimental
-- Portability :  Rank2Types
--
----------------------------------------------------------------------------
module Data.Typeable.Lens
  ( _cast
  , _gcast
  ) where

import Prelude ()

import Control.Lens
import Control.Lens.Internal.Prelude
import Data.Maybe (fromMaybe)
import Data.Typeable

-- | A 'Traversal'' for working with a 'cast' of a 'Typeable' value.
_cast :: (Typeable s, Typeable a) => Traversal' s a
_cast :: forall s a. (Typeable s, Typeable a) => Traversal' s a
_cast a -> f a
f s
s = case forall a b. (Typeable a, Typeable b) => a -> Maybe b
cast s
s of
  Just a
a  -> forall a. a -> Maybe a -> a
fromMaybe (forall a. HasCallStack => [Char] -> a
error [Char]
"_cast: recast failed") forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b. (Typeable a, Typeable b) => a -> Maybe b
cast forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> a -> f a
f a
a
  Maybe a
Nothing -> forall (f :: * -> *) a. Applicative f => a -> f a
pure s
s
{-# INLINE _cast #-}

-- | A 'Traversal'' for working with a 'gcast' of a 'Typeable' value.
_gcast :: (Typeable s, Typeable a) => Traversal' (c s) (c a)
_gcast :: forall s a (c :: * -> *).
(Typeable s, Typeable a) =>
Traversal' (c s) (c a)
_gcast c a -> f (c a)
f c s
s = case forall {k} (a :: k) (b :: k) (c :: k -> *).
(Typeable a, Typeable b) =>
c a -> Maybe (c b)
gcast c s
s of
  Just c a
a  -> forall a. a -> Maybe a -> a
fromMaybe (forall a. HasCallStack => [Char] -> a
error [Char]
"_gcast: recast failed") forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall {k} (a :: k) (b :: k) (c :: k -> *).
(Typeable a, Typeable b) =>
c a -> Maybe (c b)
gcast forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> c a -> f (c a)
f c a
a
  Maybe (c a)
Nothing -> forall (f :: * -> *) a. Applicative f => a -> f a
pure c s
s
{-# INLINE _gcast #-}