Created
May 5, 2010 23:41
-
-
Save softmechanics/391600 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE FlexibleInstances, UndecidableInstances, ContextConstraints #-} | |
{- in response to http://www.reddit.com/r/haskell/comments/bxdi2/ask_what_would_be_your_dream_xs/c0p1r55 -} | |
import Control.Monad | |
class Func m where | |
func :: m Int -> m Int | |
instance (Monad m) => Func m where | |
func = liftM (+1) | |
instance (Functor m) => Func m where | |
func = fmap (+2) | |
-- Overrides both instances above, since its context is a proper superset of the others' | |
instance (Monad m, Functor m) => Func m where | |
func = fmap (+3) | |
data MyMonad a = MyMonad a | |
deriving (Show) | |
data MyFunctor a = MyFunctor a | |
deriving (Show) | |
data MyBoth a = MyBoth a | |
deriving (Show) | |
instance Monad MyMonad where | |
return = MyMonad | |
(MyMonad x) >>= f = f x | |
instance Functor MyFunctor where | |
fmap f (MyFunctor x) = MyFunctor $ f x | |
instance Functor MyBoth where | |
fmap f (MyBoth x) = MyBoth $ f x | |
instance Monad MyBoth where | |
return = MyBoth | |
(MyBoth x) >>= f = f x | |
monad :: MyMonad Int | |
monad = return 1 | |
functor :: MyFunctor Int | |
functor = MyFunctor 1 | |
both :: MyBoth Int | |
both = MyBoth 1 | |
main = do print $ func monad | |
print $ func functor | |
print $ func both | |
{- OUTPUT: | |
MyMonad 2 | |
MyFunctor 3 | |
MyBoth 4 | |
-} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment