{- This module is part of Antisplice. Copyleft (c) 2014 Marvin Cohrs All wrongs reversed. Sharing is an act of love, not crime. Please share Antisplice with everyone you like. Antisplice is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Antisplice is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Antisplice. If not, see <http://www.gnu.org/licenses/>. -} -- | Provides a counter monad. module Game.Antisplice.Utils.Counter where import Control.Arrow import Control.Monad import Control.Monad.Trans.Class -- | A counter monad. newtype CounterT m a = Counter { runCounterT :: Int -> m (a,Int) } instance Functor m => Functor (CounterT m) where fmap f a = Counter $ \s -> fmap (first f) $ runCounterT a s instance Monad m => Monad (CounterT m) where return a = Counter $ \s -> return (a,s) m >>= f = Counter $ \s -> do (a,s') <- runCounterT m s; runCounterT (f a) s' instance MonadTrans CounterT where lift m = Counter $ \s -> do a <- m; return (a,s) -- | Typeclass for all counter monads. class Monad m => MonadCounter m where -- | Tell the current number and increment it countOn :: m Int instance Monad m => MonadCounter (CounterT m) where countOn = Counter $ \s -> return (s,s+1) -- | Run the given function inside a counter withCounter :: (Monad m,Functor m) => CounterT m a -> m a withCounter m = fmap fst $ runCounterT m 0