Personal tools

New monads/MonadUnique

From HaskellWiki

< New monads
Revision as of 17:27, 24 August 2006 by ChrisKuklewicz (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

From NewMonads, copied from old wiki.

MonadUnique

This is a simple (trivial) monad transformer for supplying unique integer values to an algorithm.

"CaleGibbard/BSDLicense"

{-# OPTIONS_GHC -fglasgow-exts #-}
 
module MonadUnique
        ( UniqueT,
          Unique,
          MonadUnique,
          fresh,
          evalUniqueT,
          evalUnique )
    where
 
import Control.Monad
import Control.Monad.State
import Control.Monad.Identity
 
newtype UniqueT m a = UniqueT (StateT Integer m a)
    deriving (Functor, Monad, MonadTrans, MonadIO)
 
newtype Unique a = Unique (UniqueT Identity a)
    deriving (Functor, Monad, MonadUnique)
 
class Monad m => MonadUnique m where
    fresh :: m Integer
 
instance (Monad m) => MonadUnique (UniqueT m) where
    fresh = UniqueT $ do
                n <- get
                put (succ n)
                return n
 
evalUniqueT (UniqueT s) = evalStateT s 0
evalUnique (Unique s) = runIdentity (evalUniqueT s)