Skip to content

Instantly share code, notes, and snippets.

@v0d1ch
Forked from dminuoso/store.hs
Last active February 5, 2019 14:47
Show Gist options
  • Save v0d1ch/fdcb69b60b6e1be183de603767654999 to your computer and use it in GitHub Desktop.
Save v0d1ch/fdcb69b60b6e1be183de603767654999 to your computer and use it in GitHub Desktop.
data Store s a = Store (s -> a) s
instance Comonad (Store s) where
extract :: Store s a -> a
extract (Store f s) = f s
-- "replacing all values with containers, and then consuming those containers again"
extend :: Store s a -> (Store s a -> b) -> Store s b
extend s f = fmap f $ duplicate s
-- verbose: Store (\x -> f' $ Store f x) s
duplicate :: Store s a -> Store s (Store s a)
duplicate (Store f s) = Store (\x -> Store f x) s
-- Read out the store at some specific position
peek :: s -> Store s a -> a
peek s (Store f _) = f s
-- Modify the current focus, and read the store using the new focus.
peeks :: (s -> s) -> Store s a -> a
peeks f (Store f' s) = f' (f s)
-- Set the current focus
seek :: s -> Store s a -> Store s a
seek s (Store f _) = Store f s
-- Modify the current focus
seeks :: (s -> s) -> Store s a -> Store s a
seeks f (Store f' s) = Store f' (f s)
-- Run an experiment in the store.
experiment :: Functor f => (s -> f s) -> Store s a -> f a
experiment f (Store s a) = fmap s (f a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment