gpt4 book ai didi

haskell - Comonads 或 Representable 上的镜头

转载 作者:行者123 更新时间:2023-12-02 16:59:55 25 4
gpt4 key购买 nike

这是这个问题的更具体的变体:Mutate only focus of Store Comonad? ,这样做的好处是不要一次提出多个问题。

是否有兼容 Control.Lens 的镜头它允许我与 comonad 的焦点(来自 extract 的值)或与 Store Comonad (pos) 的索引/值进行交互?

看起来镜片在这里可能有点用处,但我一直找不到合适的东西;任何帮助将不胜感激,谢谢!

最佳答案

Comonad 没有给你任何写回 comonad 焦点的方法,所以你不能为 extract 编写通用的 Lens >。但是it is very easy to turn any old function into a Getter :

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

当然,正如您提到的,许多comonad确实允许您写入焦点 - Store,但也(包括但不限于)Env追踪身份

-- 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 ,很容易构造一个用于 comonad 焦点的 Lens

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

关于效率的一点说明:StoreTTracedTwrite 实现构建了一个函数链,并在向下的过程中进行相等性检查,因此extractwrite 调用次数为 O(n)。既然您提到您正在使用 Representable comonad w,您可以实现一些巧妙的策略来批量编辑并将它们具体化为实际的 w每隔一段时间。或者,您可以将编辑存储在 Map 中(将 Eq 约束加强为 Ord)并委托(delegate)给底层 w当发现某个元素尚未被编辑时。我会把这部分留给你。

关于haskell - Comonads 或 Representable 上的镜头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49585295/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com