@@ -6,21 +6,23 @@ module Data.Vault
66 , insert
77 , lookup
88 , delete
9+ , union
910 ) where
1011
1112import Prelude
1213
1314import Control.Monad.Eff (Eff)
14−import Control.Monad.Eff.Unsafe (unsafeCoerceEff)
15+import Control.Monad.Eff.Unsafe (unsafePerformEff)
1516import Control.Monad.Eff.Ref (REF, Ref, newRef, writeRef, modifyRef')
1617
1718import Data.Map as M
1819import Data.Maybe (Maybe(..))
19−import Data.Newtype (class Newtype, over)
2020import Data.Vault.Internal (Unique, newUnique)
2121
22+-- | A persistent store for values of arbitrary types.
2223newtype Vault = Vault (M.Map Unique Item)
2324
25+-- | Key for an item in vault
2426data Key a = Key Unique (Item' a)
2527
2628type Item = Eff (ref :: REF) Unit
@@ -31,35 +33,31 @@ type Item' a = Ref (Maybe a)
3133empty :: Vault
3234empty = Vault M.empty
3335
36+-- | Create a new key for use with a vault.
3437newKey :: forall eff a. Eff (ref :: REF | eff) (Key a)
3538newKey = do
3639 k <- newUnique
3740 ref <- newRef Nothing
3841 pure $ Key k ref
3942
43+-- | Insert a value for a given key. Overwrites any previous value.
4044insert :: forall a. Key a -> a -> Vault -> Vault
41−insert (Key k ref) a = over Vault $ M.insert k (writeRef ref (Just a))
45+insert (Key k ref) a (Vault m) = Vault (M.insert k (writeRef ref (Just a)) m)
4246
47+-- | Delete a key from the vault.
4348delete :: forall a. Key a -> Vault -> Vault
44−delete (Key k _) = over Vault $ M.delete k
49+delete (Key k _) (Vault m) = Vault (M.delete k m)
4550
46−lookup :: forall eff a. Key a -> Vault -> Eff (ref :: REF | eff) (Maybe a)
51+-- | Lookup the value of a key in the vault.
52+lookup :: forall a. Key a -> Vault -> Maybe a
4753lookup (Key k ref) (Vault m) = case M.lookup k m of
48− Nothing -> pure Nothing
49− Just act -> do
50− _ <- coerceVaultItem act
54+ Nothing -> Nothing
55+ Just act -> unsafePerformEff do
56+ _ <- act
5157 modifyRef' ref rollItem
5258
53−coerceVaultItem :: forall eff a. Eff (ref :: REF) a -> Eff (ref :: REF | eff) a
54−coerceVaultItem = unsafeCoerceEff
59+union :: Vault -> Vault -> Vault
60+union (Vault m) (Vault n) = Vault (M.union m n)
5561
5662rollItem :: forall a. Maybe a -> { state :: Maybe a, value :: Maybe a }
5763rollItem a = { state: Nothing, value: a }
58−
59−derive instance newtypeVault :: Newtype Vault _
60−
61−instance eqKey :: Eq (Key a) where
62− eq (Key a _) (Key b _) = a == b
63−
64−instance ordKey :: Ord (Key a) where
65− compare (Key a _) (Key b _) = compare a b