Having some idea of what the Comonad typeclass is in Haskell, I've heard about the Store comonad. But looking at Control.Comonad.Store.Lazy, I don't really get it. What does it mean? What is it for? I've heard that Store = CoState, the dual of the State Monad. What does that mean?
Given the following definition of store,
data Store s a = Store { peek :: s -> a, pos :: s }
I like to think of a Store
as a big warehouse filled with values of type a
. Each value of type a
is slotted into a position labeled by an index value of type s
. Finally there is a forklift parked at position pos
. The forklift can be used to extract
a value of type a
from the store by pulling the value out from where it is parked. You can use seek
to move the forklift to a new absolute position or use seeks
to move the forklift to a new relative location. To update all values of the store use fmap
. Finally extend f
is similar to fmap
except instead of f :: a -> a'
we have f :: Store s a -> a'
which lets the update function not only have access to the value being updated but also gives access to the value's position and access to the values of everything else in the store. In other words, extend
uses the value plus its surrounding context to perform the update.
A more computery analogy would be to think of a Store
as a big platter of a hard disk with values stored at various positions, plus a head parked at a particular position.
It's much easier if you look at the definition of StoreT itself.
You can think of it as a "place" in a larger structure. For instance, a lens is just a -> Store b a
; you get the value of the b field, and a function b -> a
to put a new value back into the larger context.
Considering it in its simplified, non-transformer form:
data Store s a = Store (s -> a) s instance Functor (Store s) where fmap f (Store g s) = Store (f . g) s instance Extend (Store s) where duplicate (Store f s) = Store (Store f) s instance Comonad (Store s) where extract (Store f s) = f s
i.e. duplicate
changes the s -> a
into an s -> Store s a
that just returns the "updated" place after replacing the value, and extract
restores the original a by placing the value back into the larger structure.
As far as its relation to State goes, you could look at it like this:
type State s a = s -> (a, s) type Store s a = (s -> a, s)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With