Here's a more specific variant of this question: Mutate only focus of Store Comonad?, for the benefit of not asking more than one question at once.
Are there any lenses compatible with Control.Lens which allow me to interact with the focus of a comonad (the value from extract
) or with the index/value of the Store Comonad (pos
)?
It seems like lenses may be of some use here, but I have been unable to find anything which fits; any help would be appreciated, thanks!
Comonad
doesn't give you any way to write back to the comonad's focus, so you can't write a generalLens
forextract
. But it is very easy to turn any old function into aGetter
:Of course many comonads do allow you to write into the focus -
Store
, as you mentioned, but also (including but not limited to)Env
,Traced
andIdentity
.Given
ComonadWritable
it's easy to construct aLens
for a comonad's focus.One note on efficiency:
StoreT
andTracedT
'swrite
implementations build a chain of functions with equality checks on the way down, soextract
is O(n) in the number ofwrite
calls. Since you mentioned you're using aRepresentable
comonadw
, you could implement some clever strategy of batching up edits and reifying them into an actualw
every so often. Or you could store edits in aMap
(strengthening theEq
constraint toOrd
) and delegate to the underlyingw
when it turns out an element hasn't been edited. I'll leave that part to you.