Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Store comonad?

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?

like image 727
Dan Burton Avatar asked Jan 07 '12 00:01

Dan Burton


2 Answers

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.

like image 91
Russell O'Connor Avatar answered Sep 26 '22 12:09

Russell O'Connor


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) 
like image 41
ehird Avatar answered Sep 24 '22 12:09

ehird