5

这是这个问题的一个更具体的变体:Mutate only focus of Store Comonad? ,为了避免一次问多个问题。

是否有任何与Control.Lens兼容的镜头允许我与共单子的焦点(来自 的值extract)或与存储共单子的索引/值(pos)进行交互?

似乎镜头在这里可能有用,但我一直找不到合适的东西;任何帮助将不胜感激,谢谢!

4

1 回答 1

3

Comonad没有给你任何写回comonad的焦点的方法,所以你不能Lensextract. 但是很容易将任何旧函数变成Getter:

extracted :: Comonad w => Getter (w a) a
extracted = to extract

当然,许多comonads确实允许您写入焦点 - Store,正如您所提到的,但也(包括但不限于)EnvTracedIdentity

-- I suspect some of these laws are redundant:
--   write id = id
--   write f . write g = write (f . g)
--   extract . write f = f . extract
--   duplicate . write f = write (write f) . duplicate
--   write (const (extract w)) w = w
class Comonad w => ComonadWritable w where
    write :: (a -> a) -> w a -> w a

instance ComonadWritable Identity where
    write f (Identity x) = Identity (f x)

-- law-abiding "up to Eq"
instance (Eq s, ComonadWritable w) => ComonadWritable (StoreT s w) where
    write f (StoreT w s) = StoreT (write g w) s
        where
            g k s'
                | s' == s = f (k s')
                | otherwise = k s'

-- law-abiding "up to Eq"
instance (Eq m, Monoid m, ComonadWritable w) => ComonadWritable (TracedT m w) where
    write f (TracedT w) = TracedT (write g w)
        where
            g k m
                | m == mempty = f (k m)
                | otherwise = k m

instance ComonadWritable w => ComonadWritable (EnvT e w) where
    write f (EnvT e w) = EnvT e (write f w)

鉴于ComonadWritable很容易Lens为一个comonad的焦点构建一个。

focus :: ComonadWritable w => Lens' (w a) a
focus = lens extract (\w x -> write (const x) w)

关于效率的一个注意事项:StoreTandTracedTwrite实现构建了一系列函数,并在下降过程中进行相等检查,调用extract次数也是 O(n) 。write既然你提到你正在使用一个Representablecomonad w,你可以实施一些巧妙的策略来批量编辑并经常将它们具体化为实际w。或者,您可以将编辑存储在 a 中Map(加强对 的Eq约束),并在发现元素未被编辑时Ord委托给底层。w我会把那部分留给你。

于 2018-03-31T10:53:43.733 回答