runState (liftM (+100) pop) [1, 2, 3, 4] (Example from LYH)

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

runState (liftM (+100) pop) [1, 2, 3, 4] (Example from LYH)

Olumide
Dear List,

Apologies for the awkward question title -- its the best I can do ATM.
I'm still working my way through chapter 13 of LYH (title for a few
monads more) and I came across the following two beasts

ghci> runState (liftM (+100) pop) [1,2,3,4]
(101,[2,3,4])
ghci> runState (fmap (+100) pop) [1,2,3,4]
(101,[2,3,4])
See
http://learnyouahaskell.com/for-a-few-monads-more#useful-monadic-functions

Even though I'm still struggling to wrap my mind around monads, I sort
of understand what's going on here. The problem is that I can't explain
why the function (+100) is applied to _only_ the value 1 in (1,[2,3,4]).

Regards,

- Olumide
_______________________________________________
Beginners mailing list
[hidden email]
http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
Reply | Threaded
Open this post in threaded view
|

Re: runState (liftM (+100) pop) [1, 2, 3, 4] (Example from LYH)

Francesco Ariis
On Tue, Oct 24, 2017 at 10:17:46AM +0100, Olumide wrote:
> ghci> runState (fmap (+100) pop) [1,2,3,4]
> (101,[2,3,4])
>
> Even though I'm still struggling to wrap my mind around monads, I sort of
> understand what's going on here. The problem is that I can't explain why the
> function (+100) is applied to _only_ the value 1 in (1,[2,3,4]).

Hello Olumide,
    if we look at the instance of `fmap` for State we'll find (more or
less):

    fmap :: (a -> b) -> State s a -> State s b

So fmap modifies the *result*, not the *state* itself.

If we also recall that `State s a` is nothing but `\s -> (a, s)` then
it is easy to see that only the first element of the tuple (the
so called result, `a`) will be modified.

Does this clear your doubts?
_______________________________________________
Beginners mailing list
[hidden email]
http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners