module Yi.Dynamic
(
Initializable(..),
toDyn, fromDynamic, dynamicValueA, emptyDV,
Typeable, Dynamic, DynamicValues
)
where
import Prelude ()
import Yi.Prelude
import GHC.Exts
import Data.Accessor
import Data.Maybe
import Data.Typeable
import Data.Map as M
class (Typeable a) => Initializable a where
initial :: a
data Dynamic = forall a. Initializable a => Dynamic a
type DynamicValues = M.Map String Dynamic
toDyn :: Initializable a => a -> Dynamic
toDyn = Dynamic
fromDynamic :: forall a. Typeable a => Dynamic -> Maybe a
fromDynamic (Dynamic b) = if typeOf (undefined :: a) == typeOf b then Just (unsafeCoerce# b) else Nothing
instance (Typeable a) => Initializable (Maybe a) where
initial = Nothing
dynamicValueA :: Initializable a => Accessor DynamicValues a
dynamicValueA = accessor getDynamicValue setDynamicValue
where
setDynamicValue :: forall a. Initializable a => a -> DynamicValues -> DynamicValues
setDynamicValue v = M.insert (show $ typeOf (undefined::a)) (toDyn v)
getDynamicValue :: forall a. Initializable a => DynamicValues -> a
getDynamicValue dv = case M.lookup (show $ typeOf (undefined::a)) dv of
Nothing -> initial
Just x -> fromJust $ fromDynamic x
emptyDV :: DynamicValues
emptyDV = M.empty