[Haskell-cafe] Re: What I wish someone had told me...

Bulat Ziganshin bulat.ziganshin at gmail.com
Wed Oct 15 12:04:48 EDT 2008


Hello David,

Wednesday, October 15, 2008, 7:16:09 PM, you wrote:

> I've read a lot of the Monad tutorials, and I feel like I only get
> "most of it" to be 100% honest.  The State Monad still boggles my
> mind a little bit.  I understand what it's supposed to do and I get
> the idea about how it works.  It's just that when I look at the
> implementation of >>= for it, I want to crawl into a corner and nibble my fingers.

may be i can help? :)  all those pure monads imho is rather
straightforward - monad just carries some value inside (such as state,
environment, or data logged) and >>=,>> operations bind actions while
carrying this value hiddenly. only get/set operations interact with
this value while for >>=,>> operations the only requirement is to pas
input value into first operation, then pass value at the exit of first
operation and pass it to second one and finally return value returned
by second operation. smth like this:

for state monad every action has its own (imparative) result of type a
plus receives some State and returns some State:

type StateAction a  =  State -> (a,State)

(>>) :: StateAction a -> StateAction b -> StateAction ()
-- this means that >> is operation on two actions which joins them and
-- return composed action

action1 >> action2  =
  -- Result of joining two actions is action again
  -- i.e. it has type State -> ((),State)
  -- so we define it as a function which receives initial state
  -- and carries it through both actions sequentially
  -- finally returning state returned from last action
  \state0 -> let (_,state1) = action1 state0
                 (_,state2) = action2 state1
             in ((),state2)

then when we apply (action1 >> action2) to some state this is
calculated as action1 calculation performed on this state and then
action2 calculation pewrformed on the state returned from action1

if you are are easy with high-order functions, partial application and
carrying you should have no problems mastering monads


-- 
Best regards,
 Bulat                            mailto:Bulat.Ziganshin at gmail.com



More information about the Haskell-Cafe mailing list