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

问题描述

有人可以向我解释功能镜头吗?对于谷歌来说这是一个令人惊讶的难题,我还没有取得任何进展。我所知道的是他们提供了类似于OO的get / set功能。

解决方案

镜头由两个功能组成,和setter:

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

例如,我们可能会在一对中的第一部分和第二部分使用镜头: p>

  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 bc  - >镜头a b  - >镜头a c 
组合f g = Lens(getter f。getter g)$
\c a - > setter g(setter fc(getter ga))a

然后它们机械地转换为 State 转换:

  lensGet :: MonadState sm =>镜头s  -   - > m a 
lensGet =获得。 getter

lensSet :: MonadState s m =>镜头s b - > b - > m()
lensSet f =修改。 setter f

lensMod :: MonadState s m =>镜头s b - > (b→b)→> m()
lensMod f g =修改$ setter f =<< G 。 getter f

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


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.

解决方案

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)

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

09-21 19:56