haskell - “凋零”的 Profunctor 表示是什么?
问题描述
Chris Penner 的这篇文章谈到了“Witherable Optics”;可用于从结构中过滤项目的光学元件。
本文对这些光学器件使用以下“Van Laarhoven”表示:
type Wither s t a b = forall f. Alternative f => (a -> f b) -> s -> f t
大多数(如果不是全部)Van Laarhoven 光学具有等效的 profunctor 表示。例如镜头:
type Lens s t a b = forall f. Functor f => (a -> f b) -> s -> f t
相当于:
type Lens s t a b = forall p. Strong p => p a b -> p s t
是否Wither
也有生产者代表?如果是这样,那是什么?
解决方案
克里斯在这里;这是我对 Profunctor 光学表示的看法:
import Data.Profunctor
import Data.Profunctor.Traversing
import Control.Applicative
class (Traversing p) => Withering p where
cull :: (forall f. Alternative f => (a -> f b) -> (s -> f t)) -> p a b -> p s t
instance Alternative f => Withering (Star f) where
cull f (Star amb) = Star (f amb)
instance Monoid m => Withering (Forget m) where
cull f (Forget h) = Forget (getAnnihilation . f (AltConst . Just . h))
where
getAnnihilation (AltConst Nothing) = mempty
getAnnihilation (AltConst (Just m)) = m
newtype AltConst a b = AltConst (Maybe a)
deriving stock (Eq, Ord, Show, Functor)
instance Monoid a => Applicative (AltConst a) where
pure _ = (AltConst (Just mempty))
(AltConst Nothing) <*> _ = (AltConst Nothing)
_ <*> (AltConst Nothing) = (AltConst Nothing)
(AltConst (Just a)) <*> (AltConst (Just b)) = AltConst (Just (a <> b))
instance (Semigroup a) => Semigroup (AltConst a x) where
(AltConst Nothing) <> _ = (AltConst Nothing)
_ <> (AltConst Nothing) = (AltConst Nothing)
(AltConst (Just a)) <> (AltConst (Just b)) = AltConst (Just (a <> b))
instance (Monoid a) => Monoid (AltConst a x) where
mempty = (AltConst (Just mempty))
instance Monoid m => Alternative (AltConst m) where
empty = (AltConst Nothing)
(AltConst Nothing) <|> a = a
a <|> (AltConst Nothing) = a
(AltConst (Just a)) <|> (AltConst (Just b)) = (AltConst (Just (a <> b)))
如果您对出现的一些光学器件感兴趣,我在这里实现了其中的一些:
绝对有可能有其他解释或一些更简单的表示,但目前这似乎可以解决问题。如果其他人有其他想法,我很乐意看到他们!
如果您有任何其他问题,很乐意多聊!
推荐阅读
- java - 动画 java.lang.NullPointerException 错误
- wordpress - 将 Wordpress 实时站点转换为 PWA 的最佳实践是什么
- android - 为什么 Toast 消息会重置我的手机?
- php - 如果“投票”表中不存在客户端 IP,如何正确添加费率
- java - 如何将谷歌地图标记异步添加到地图?
- c - 无法使用 c 中的套接字接收大型数组
- laravel - 如果验证问题需要 Laravel
- php - PHP 从字符串中替换图像
- java - Community Edition 内置 Java 项目模板是否忽略语言级别?
- node-modules - ng cli new 命令:使用父目录中的 node_modules