[Haskell-cafe] How to spot Monads, Applicatives ...

Albert Y. C. Lai trebla at vex.net
Wed Jun 15 17:10:36 UTC 2016


On 2016-06-15 11:54 AM, martin wrote:
> Paticularly I am having difficulties with the *->* instances. E.g. why is the state "s" in the state monad the fixed
> type and the "a" the type parameter? When I am writing state code without the State monad the two look like equal
> candidates. Why not have "State a" monad, which threads an a-typed value and spits out states?

You mean like this?

newtype MyState a s = Mk {unMk :: a -> (s, a)}

thread_a_and_spit_out_s :: MyState a s -> a -> s
thread_a_and_spit_out_s (Mk h) a = case h a of (s, _) -> s

instance Monad (MyState a) where
     -- return :: s -> MyState a s
     return s = Mk (\a -> (s, a))
     -- (>>=) :: MyState a s -> (s -> MyState a t) -> MyState a t
     Mk h >>= k = Mk (\a0 ->
         case h a0 of (s, a1) -> unMk (k s) a1)

instance Functor (MyState a) where
     -- fmap :: (s -> t) -> MyState a s -> MyState a t
     fmap f (Mk h) = Mk (\a0 -> case (h a0) of (s, a1) -> (f s, a1))

instance Applicative (MyState a) where
     pure = return
     mf <*> mx = mf >>= \f -> mx >>= \x -> return (f x)

> While we're at it: would someone be so kind and explain what exactly is meant by an "effect"? I know that in haskell
> this is not the same as a "side effect" as there are no side-effects in haskell.

It is just a change of attitude. I say "effect" when it is a purpose of 
my program, in fact likely a main purpose. I say "side effect" when it 
is not a purpose of my program.

But since I write programs by intelligent design rather than by 
evolution, of course everything my program does is on purpose.

The name "side effect" was coined when people had dispute over whether 
"function" should mean inert mathematical function or interactive 
computational procedure.


More information about the Haskell-Cafe mailing list