[Haskell-beginners] Applicative for State

Francesco Ariis fa-ml at ariis.it
Mon Feb 6 20:15:29 UTC 2017


On Mon, Feb 06, 2017 at 07:40:12PM +0000, mike h wrote:
> I have a State by another name, Stat,  just to experiment and learn.
> [...]
> I really can’t get what the <*> in the Applicative should be!
> I just do see how I ‘get the f out of the Stat’ and then apply it.
> 
> I’d be really grateful if someone would explain what it should be and
> the steps/reasoning needed to get there.

Hello Mike,

    when writing an instance, you always have to keep in mind: (a) the
signature of the function you are writing and (b) what the instance
is designed to do.

In our case, (<*>) is:

    (<*>) :: Applicative f => f (a -> b) -> f a -> f b

    -- which we could 'rewrite' as
    (<*>) ::  Stat s (a -> b) -> Stat s a -> Stat s b

so we grab the results, one being a function and the other a value,
and apply the first to the second.

(b) is "pass the state around in the background". Good, let's put this
in action:

    (Stat f) <*> (Stat g) = Stat $ \s ->
        let (h, s')  = f s     -- h is a function :: a -> b
            (a, s'') = g s'    -- state passing
            b        = h a in  -- the application
        (b, s'') -- we're not returning just the tuple, we're returning
                 -- even the bit before the 'let' statement

And that is that. Was this clear?


More information about the Beginners mailing list