简体   繁体   English

如何将Lens定义为State值本身?

[英]How to define Lens into the State value itself?

While trying to understand State monad and use of Lens with it, I arrived at a surprisingly trivial definition of a lens for a simple counter: 在试图理解State monad并使用Lens时,我得到了一个简单的计数器镜头的惊人定义:

self :: ASetter s s s s
self = ($)

incrementUsingLens :: State Int ()
incrementUsingLens = self %= (+1)

Since 以来

type ASetter s t a b = (a -> Identity b) -> s -> Identity t

In my case is just 在我的情况下只是

type ASetter s s s s = (s -> Identity s) -> s -> Identity s

Is this is indeed a correct definition for a lens into a state variable? 对于镜头变成状态变量,这确实是一个正确的定义吗? I'm worried that I might be missing some laws or other assumptions. 我担心我可能会遗漏一些法律或其他假设。

lens calls this do-nothing optic simple . 镜头称之为无操作光学simple Note that simple is an Equality , and Equality is at the very bottom of the optics hierarchy, which means you can use it not only as a do-nothing setter, but also as a do-nothing lens, prism, etc. 请注意, simple是一个EqualityEquality位于光学层次结构的最底层,这意味着你不仅可以将它用作无用设置器,还可以用作无操作镜头,棱镜等。

I'm worried that I might be missing some laws or other assumptions. 我担心我可能会遗漏一些法律或其他假设。

The setter laws say that, for a foo setter, over foo should follow the functor laws: 制定者的法律规定,对于foo setter来说, over foo应遵循仿函数法则:

over foo id = id
over foo (g . f) = over foo g . over foo f

If you try this with simple / id , you will find the laws hold trivially. 如果您使用simple / id尝试此操作,您会发现法律保持平凡。 The same goes for the other optic laws. 其他光学法则也是如此。

Yes, ($) , also called id , is also a lens in the representation of the lens package. 是的, ($) ,也称为id ,也是镜头包装中的镜头。 Though here we have get , put , modify that work just as well, the identity lens can still be useful sometimes. 虽然在这里我们也getputmodify这项工作,但身份镜头有时仍然有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM