Skip to content

Instantly share code, notes, and snippets.

@softmechanics
Created May 5, 2010 23:41
Show Gist options
  • Save softmechanics/391600 to your computer and use it in GitHub Desktop.
Save softmechanics/391600 to your computer and use it in GitHub Desktop.
{-# 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