功能镜片 [英] Functional lenses

查看:15
本文介绍了功能镜片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

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

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

他们机械地转换为State转换:

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)

这篇关于功能镜片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆