Use data-accessor-transformers package to remove deprecation warnings
[matthijs/master-project/cλash.git] / cλash / CLasH / Utils.hs
1 module CLasH.Utils where
2
3 -- Standard Imports
4 import qualified Maybe
5 import Data.Accessor
6 import Data.Accessor.Monad.Trans.State as MonadState
7 import qualified Data.Map as Map
8 import qualified Control.Monad as Monad
9 import qualified Control.Monad.Trans.State as State
10
11 -- GHC API
12
13 -- Local Imports
14   
15 -- Make a caching version of a stateful computatation.
16 makeCached :: (Monad m, Ord k) =>
17   k -- ^ The key to use for the cache
18   -> Accessor s (Map.Map k v) -- ^ The accessor to get at the cache
19   -> State.StateT s m v -- ^ How to compute the value to cache?
20   -> State.StateT s m v -- ^ The resulting value, from the cache or freshly
21                         --   computed.
22 makeCached key accessor create = do
23   cache <- MonadState.get accessor
24   case Map.lookup key cache of
25     -- Found in cache, just return
26     Just value -> return value
27     -- Not found, compute it and put it in the cache
28     Nothing -> do
29       value <- create
30       MonadState.modify accessor (Map.insert key value)
31       return value
32
33 unzipM :: (Monad m) =>
34   m [(a, b)]
35   -> m ([a], [b])
36 unzipM = Monad.liftM unzip
37
38 catMaybesM :: (Monad m) =>
39   m [Maybe a]
40   -> m [a]
41 catMaybesM = Monad.liftM Maybe.catMaybes
42
43 concatM :: (Monad m) =>
44   m [[a]]
45   -> m [a]
46 concatM = Monad.liftM concat
47
48 isJustM :: (Monad m) => m (Maybe a) -> m Bool
49 isJustM = Monad.liftM Maybe.isJust
50
51 andM, orM :: (Monad m) => m [Bool] -> m Bool
52 andM = Monad.liftM and
53 orM = Monad.liftM or
54
55 mapAccumLM :: (Monad m) => (acc -> x -> m (acc, y)) -> acc -> [x] -> m (acc, [y])
56 mapAccumLM _ s []        =  return (s, [])
57 mapAccumLM f s (x:xs)    =  do
58   (s',  y ) <- f s x
59   (s'', ys) <- mapAccumLM f s' xs
60   return (s'', y:ys)