forked from frank-lang/frank
-
Notifications
You must be signed in to change notification settings - Fork 1
/
FreshNames.hs
38 lines (29 loc) · 1.13 KB
/
FreshNames.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
{-# LANGUAGE GeneralizedNewtypeDeriving,StandaloneDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances,UndecidableInstances #-}
module FreshNames where
import Control.Monad.State
import Control.Monad.Identity
import Control.Monad.Except
import Control.Monad.Fail
-- this monad will supply fresh and is really a state monad transformer
newtype FreshMT m a = Fresh { unFresh :: StateT Int m a }
deriving (Functor, Applicative, Monad,
MonadState Int)
class Monad m => GenFresh m where
fresh :: m Int
evalFreshMT :: Monad m => FreshMT m a -> m a
evalFreshMT m = evalStateT (unFresh m) 0
evalFresh :: FreshMT Identity a -> a
evalFresh m = evalState (unFresh m) 0
instance Monad m => GenFresh (FreshMT m) where
fresh = do n <- get
put $ n + 1
return n
instance GenFresh m => GenFresh (StateT s m) where
fresh = lift fresh
instance MonadTrans FreshMT where
lift = Fresh . lift
instance MonadError e m => MonadError e (FreshMT m) where
throwError = lift . throwError
catchError m h = Fresh $ catchError (unFresh m) (unFresh . h)