{-# LANGUAGE Safe #-} {- This module is part of Chatty. Copyleft (c) 2014 Marvin Cohrs All wrongs reversed. Sharing is an act of love, not crime. Please share Chatty with everyone you like. Chatty 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. Chatty 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 Chatty. If not, see . -} -- | Provides a counter monad. module Data.Chatty.Counter where import Control.Applicative 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 (Functor m,Monad m) => Applicative (CounterT m) where pure = return (<*>) = ap 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 => ChCounter m where -- | Tell the current number and increment it countOn :: m Int instance Monad m => ChCounter (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