Skip to content

Instantly share code, notes, and snippets.

@davidallsopp
Last active August 29, 2015 14:08
Show Gist options
  • Select an option

  • Save davidallsopp/adc58deadf7de9660578 to your computer and use it in GitHub Desktop.

Select an option

Save davidallsopp/adc58deadf7de9660578 to your computer and use it in GitHub Desktop.
Implementing the Trivial Monad in haskell, including Applicative and Functor instances (required by recent GHC versions)
module TrivialMonad where
-- See also http://hackage.haskell.org/package/transformers-0.4.1.0/docs/src/Data-Functor-Identity.html#Identity
import Control.Applicative (Applicative(..)) -- import type and all exported constructors using '(..)'
-- How is that different from "import Control.Applicative"
import Control.Monad (liftM, ap)
data Trivial a = Trivial a deriving (Show) -- wrapper type
instance Monad Trivial where
return = Trivial
Trivial x >>= f = f x
-- To avoid compiler warnings about GHC 7.10 onwards,
-- derive functor and applicative from monad as per
-- http://www.haskell.org/haskellwiki/Functor-Applicative-Monad_Proposal
instance Functor Trivial where
fmap = liftM
instance Applicative Trivial where
pure = return
(<*>) = ap
-- Various articles stress the fact that there's no universal function to extract values from
-- a monad; yet many of the individual instances have just such a function (runWriter etc)
runTrivial :: Trivial a -> a
runTrivial (Trivial x) = x
main :: IO ()
main = putStrLn . runTrivial $ Trivial "Hello" >>= Trivial . reverse
-- See also http://www.haskell.org/haskellwiki/All_About_Monads#No_way_out
-- But in this case we can just pattern match to extract the value:
main2 :: IO ()
main2 = do
let Trivial t = Trivial "Hello" >>= Trivial . reverse
putStrLn t
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment