Tomer
Tomer

Reputation: 1229

Converting expression with >>= to do notation

I have the following code

newtype State s a = State { runState :: s -> (s,a) }    
evalState :: State s a -> s -> a
evalState sa s = snd $ runState sa s

instance Functor (State s) where
  fmap f sa = State $ \s ->
    let (s',a) = runState sa s in
      (s',f a)

instance Applicative (State s) where
  pure a = State $ \s -> (s,a)

  sf <*> sa = State $ \s ->
    let (s',f) = runState sf s
        (s'',a) = runState sa s' in
      (s'', f a)

instance Monad (State s) where
  sa >>= k = State $ \s ->
    let (s',a) = runState sa s in
      runState (k a) s'

get :: State s s
get = State $ \s -> (s,s)

set :: s -> State s ()
set s = State $ \_ -> (s,())

bar (acc,n) = if n <= 0
              then return ()
              else
              set (n*acc,n-1)

f x = factLoop

factLoop =  get >>= bar >>= f

And

 runState factLoop (1,7)

gives ((5040,0),())

I'm trying to write the function

 factLoop =  get >>= bar >>= f

using the do notation

I tried

 factLoop' =  do
                (x,y) <- get 
                h <-  bar (x,y) 
                return ( f h) 

But that does not give the correct type which should be State (Int, Int) ()

Any idea ?

Thanks!

Upvotes: 1

Views: 158

Answers (2)

Will Ness
Will Ness

Reputation: 71119

>>= is infixl 1 (left-associating binary operator), so what you really have is

f x = factLoop

factLoop =  get >>= bar >>= f
         =  (get >>= bar) >>= f
         =  (get >>= bar) >>= (\x -> f x)
         = do { x <- (get >>= bar)
              ; f x }
         = do { _ <- (get >>= bar)
              ; factLoop }
         = do { _ <- (get >>= (\x -> bar x))
              ; factLoop }
         = do { _ <- do { x <- get 
                        ; bar x }
              ; factLoop }
         = do { x <- get 
              ; _ <- bar x 
              ; factLoop }

the last one is because of the monad associativity law ("Kleisli composition forms a category").

Doing this in the principled way you don't need to guess. After a little while you get a feeling for it of course, but until you do, being formal helps.

Upvotes: 1

Robin Zigmond
Robin Zigmond

Reputation: 18259

Just remove the return on the final line :

factLoop' =  do
                (x,y) <- get 
                h <-  bar (x,y) 
                f h

There is no return in your original code, so there should be none in the do notation version either. do notation simply "translates" uses of >>=, as you've already done.

Upvotes: 7

Related Questions