[Haskell-cafe] Re: The mother of all functors/monads/categories
Edward Kmett
ekmett at gmail.com
Sun Jun 27 17:20:03 EDT 2010
On Sun, Jun 27, 2010 at 6:25 AM, Max Bolingbroke <batterseapower at hotmail.com
> wrote:
> By the way, you can use this stuff to solve the restricted monad
> problem (e.g. make Set an instance of Monad). This is not that useful
> until we find out what the mother of all MonadPlus is, though, because
> we really need a MonadPlus Set instance.
>
> Code below.
>
> Cheers,
> Max
>
> \begin{code}
> {-# LANGUAGE RankNTypes #-}
> import Control.Applicative
>
> import Data.Set (Set)
> import qualified Data.Set as S
>
>
> newtype CodensityOrd m a = CodensityOrd { runCodensityOrd :: forall b.
> Ord b => (a -> m b) -> m b }
>
> -- liftCodensityOrd :: Monad m => m a -> CodensityOrd m a
> -- liftCodensityOrd m = CodensityOrd ((>>=) m)
>
> -- lowerCodensityOrd :: (Ord a, Monad m) => CodensityOrd m a -> m a
> -- lowerCodensityOrd m = runCodensityOrd m return
>
> instance Functor (CodensityOrd f) where
> fmap f m = CodensityOrd (\k -> runCodensityOrd m (k . f))
>
> instance Applicative (CodensityOrd f) where
> pure x = CodensityOrd (\k -> k x)
> mf <*> mx = CodensityOrd (\k -> runCodensityOrd mf (\f ->
> runCodensityOrd mx (\x -> k (f x))))
>
> instance Monad (CodensityOrd f) where
> return = pure
> m >>= k = CodensityOrd (\c -> runCodensityOrd m (\a ->
> runCodensityOrd (k a) c))
>
>
>
> liftSet :: Ord a => Set a -> CodensityOrd Set a
> liftSet m = CodensityOrd (bind m)
> where bind :: (Ord a, Ord b) => Set a -> (a -> Set b) -> Set b
> mx `bind` fxmy = S.fold (\x my -> fxmy x `S.union` my) S.empty mx
>
> lowerSet :: Ord a => CodensityOrd Set a -> Set a
> lowerSet m = runCodensityOrd m S.singleton
>
>
> main = print $ lowerSet $ monadicPlus (liftSet $ S.fromList [1, 2, 3])
> (liftSet $ S.fromList [1, 2, 3])
>
> monadicPlus :: Monad m => m Int -> m Int -> m Int
> monadicPlus mx my = do
> x <- mx
> y <- my
> return (x + y)
>
> \end{code}
>
I've pointed out the Codensity Set monad on the Haskell channel. It is an
interesting novelty, but it unfortunately has somewhat funny semantics in
that the intermediate sets that you obtain are based on what you would get
if you reparenthesized all of your binds and associating them to the right.
One way to think about how Codensity adjusts a monad is that it can take
something that is almost a monad (you need to get in and out of Codensity).
Another thing to note is that Codensity is slightly more powerful than the
original type you embedded.
An interesting example is that you can show that Codensity Reader ~ State.
Take a look at the code in monad-ran on hackage for how Ran (StateT s m) is
implemented for an example.
-Edward Kmett
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20100627/425710ec/attachment.html
More information about the Haskell-Cafe
mailing list