Add andM and orM utility functions.
[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 qualified Data.Map as Map
7 import qualified Control.Monad as Monad
8 import qualified Control.Monad.Trans.State as State
9
10 -- GHC API
11
12 -- Local Imports
13   
14 -- Make a caching version of a stateful computatation.
15 makeCached :: (Monad m, Ord k) =>
16   k -- ^ The key to use for the cache
17   -> Accessor s (Map.Map k v) -- ^ The accessor to get at the cache
18   -> State.StateT s m v -- ^ How to compute the value to cache?
19   -> State.StateT s m v -- ^ The resulting value, from the cache or freshly
20                         --   computed.
21 makeCached key accessor create = do
22   cache <- getA accessor
23   case Map.lookup key cache of
24     -- Found in cache, just return
25     Just value -> return value
26     -- Not found, compute it and put it in the cache
27     Nothing -> do
28       value <- create
29       modA accessor (Map.insert key value)
30       return value
31
32 unzipM :: (Monad m) =>
33   m [(a, b)]
34   -> m ([a], [b])
35 unzipM = Monad.liftM unzip
36
37 catMaybesM :: (Monad m) =>
38   m [Maybe a]
39   -> m [a]
40 catMaybesM = Monad.liftM Maybe.catMaybes
41
42 concatM :: (Monad m) =>
43   m [[a]]
44   -> m [a]
45 concatM = Monad.liftM concat
46
47 isJustM :: (Monad m) => m (Maybe a) -> m Bool
48 isJustM = Monad.liftM Maybe.isJust
49
50 andM, orM :: (Monad m) => m [Bool] -> m Bool
51 andM = Monad.liftM and
52 orM = Monad.liftM or