首页 文章

什么是商店comonad?

提问于
浏览
41

what the Comonad typeclass is in Haskell有所了解,我听说过Store comonad . 但是看着Control.Comonad.Store.Lazy,我没听说过Store = CoState,这是State Monad的双重身份 . 那是什么意思?

2 回答

  • 35

    如果你看一下StoreT itself的定义会容易得多 .

    您可以将其视为更大结构中的"place" . 例如,lens只是 a -> Store b a ;你得到了b字段的值,并且函数 b -> a 将一个新值放回到更大的上下文中 .

    以简化的非变压器形式考虑它:

    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
    

    duplicates -> a 更改为 s -> Store s a ,仅在替换值后返回"updated"位置, extract 通过将值放回较大的结构来恢复原始a .

    至于它与国家的关系,你可以这样看:

    type State s a = s -> (a, s)
    type Store s a = (s -> a, s)
    
  • 41

    鉴于商店的以下定义,

    data Store s a = Store { peek :: s -> a, pos :: s }
    

    我想将 Store 想象成一个充满 a 类型值的大仓库 . 类型 a 的每个值都被插入到由 s 类型的索引值标记的位置 . 终于有一辆停在 pos 位置的叉车 . 叉车可以通过从停车位置拉出值来从商店使用 a 类型的值 . 您可以使用 seek 将叉车移动到新的绝对位置,或使用 seeks 将叉车移动到新的相对位置 . 要更新商店的所有值,请使用 fmap . 最后 extend f 类似于 fmap ,除了 f :: a -> a' ,我们有 f :: Store s a -> a' ,这使得更新功能不仅可以访问正在更新的值,还可以访问值的位置并访问商店中其他所有值的值 . 换句话说, extend 使用该值加上其周围的上下文来执行更新 .

    更为计算机的类比是将 Store 视为硬盘的大盘,其值存储在不同位置,加上停放在特定位置的头部 .

相关问题