[Haskell-beginners] basic Functor, Applicative and Monad instances

Imants Cekusins imantc at gmail.com
Fri Jul 17 07:53:01 UTC 2015


based on this snippet and Rein's comment, here is monad file template
for intellij Idea to make new monads a quick exercise:

module ${PACKAGE_NAME}.${NAME} where


data ${Type} a = ${ctor} {
    ${prop}::a
}


instance Functor ${Type} where
-- (a -> b) -> f a -> f b
--   fmap f (${ctor} x) = ${ctor} (f x)
   fmap ab fa = let  a1 = ${prop} fa
                     b1 = ab a1
                in fa { ${prop} = b1 }


instance Applicative ${Type} where
-- a -> f a
--  pure = ${ctor}
   pure a =  ${ctor} { ${prop} = a }

-- f (a -> b) -> f a -> f b
--   ${ctor} f <*> ${ctor} x = ${ctor} (f x)
   (<*>) fab fa =  let  ab1 = ${prop} fab
                        a1 = ${prop} fa
                        b1 = ab1 a1
                   in fa { ${prop} = b1 }


instance Monad ${Type} where
-- a -> m a
   return a = ${ctor} { ${prop} = a }

--  m a -> (a -> m b) -> m b
   (>>=) ma amb = let a1 = ${prop} ma
                 in amb a1


More information about the Beginners mailing list