功能性镜片

发布于 2024-12-18 21:30:47 字数 85 浏览 0 评论 0原文

有人可以向我解释一下功能性镜片吗?对于谷歌来说,这是一个令人惊讶的困难主题,而且我还没有取得任何进展。我所知道的是它们提供了与 OO 类似的获取/设置功能。

Could someone explain functional lenses to me? It's a surprisingly difficult subject to google for and I haven't made any progress. All I know is that they provide similar get/set functionality than in OO.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

旧时模样 2024-12-25 21:30:47

透镜由两个函数组成,一个 getter 和一个 setter:

data Lens a b = Lens { getter :: a -> b, setter :: b -> a -> a }

例如,我们可能有一对透镜的第一部分和第二部分:

fstLens :: Lens (a, b) a
fstLens = Lens fst $ \x (a, b) -> (x, b)

sndLens :: Lens (a, b) b
sndLens = Lens snd $ \x (a, b) -> (a, x)

透镜的真正便利之处在于它们组成:

compose :: Lens b c -> Lens a b -> Lens a c
compose f g = Lens (getter f . getter g) $
                   \c a -> setter g (setter f c (getter g a)) a

并且它们会机械地转换为 State< /代码> 转换:

lensGet :: MonadState s m => Lens s a -> m a
lensGet = gets . getter

lensSet :: MonadState s m => Lens s b -> b -> m ()
lensSet f = modify . setter f

lensMod :: MonadState s m => Lens s b -> (b -> b) -> m ()
lensMod f g = modify $ setter f =<< g . getter f

(+=) :: (MonadState s m, Num b) => Lens s b -> b -> m ()
f += x = lensMod f (+ x)

A lens consists of two functions, a getter and a setter:

data Lens a b = Lens { getter :: a -> b, setter :: b -> a -> a }

For example, we might have lenses for the first and second parts of a pair:

fstLens :: Lens (a, b) a
fstLens = Lens fst $ \x (a, b) -> (x, b)

sndLens :: Lens (a, b) b
sndLens = Lens snd $ \x (a, b) -> (a, x)

The real convenience of lenses is that they compose:

compose :: Lens b c -> Lens a b -> Lens a c
compose f g = Lens (getter f . getter g) $
                   \c a -> setter g (setter f c (getter g a)) a

And they mechanically convert to State transitions:

lensGet :: MonadState s m => Lens s a -> m a
lensGet = gets . getter

lensSet :: MonadState s m => Lens s b -> b -> m ()
lensSet f = modify . setter f

lensMod :: MonadState s m => Lens s b -> (b -> b) -> m ()
lensMod f g = modify $ setter f =<< g . getter f

(+=) :: (MonadState s m, Num b) => Lens s b -> b -> m ()
f += x = lensMod f (+ x)
淡淡離愁欲言轉身 2024-12-25 21:30:47

请参阅问题的答案镜头、fclabels、数据-accessor - 哪个结构访问和突变库更好 - 它对镜头有非常清晰的解释。

此外,还有数据的文档。镜头fclabel 库提供了一些很好的使用示例。

See the answer to question lenses, fclabels, data-accessor - which library for structure access and mutation is better - it has a very clear explanation on lenses.

Also, the documentation for the Data.Lenses and fclabel libraries give some good examples of them being used.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文