问题描述
有一个Scalaz地图镜头的例子:丹伯顿称它为$ code> containsKey ,它的灵感来自爱德华·凯特的话。在Scalaz 7中还有一些名为 mapVPLens
的东西,这对于修改地图中的值是有用的。
There's an example of a Scalaz map lens here: Dan Burton calls it containsKey
, and it's inspired by the Edward Kmett talk. There is also something called mapVPLens
in Scalaz 7 which is useful for modifying values in a map.
我的问题是:如果我有一个镜头修改类型 V
,以及一个映射[K,V]
的镜头,我可以组合他们吗?我一直在寻找一个很好的简单例子,但在Scalaz还没有一些例子。
My question is: if I have a lens for modifying type V
, and a lens for a Map[K,V]
, how can I compose them? I've been searching for a while for a good simple example, but there's still a dearth of examples in Scalaz.
我对Scalaz 6和Scalaz 7解决方案感兴趣。
I'm interested in both Scalaz 6 and Scalaz 7 solutions.
推荐答案
如果您尝试使用地图镜头组合的镜头是部分镜头,则可以使用撰写
:
If the lens you're trying to compose with the map lens is a partial lens, you can just use compose
:
import scalaz._, Scalaz._, PLens._
def headFoo[A] = listHeadPLens[A] compose mapVPLens("foo")
然后:
scala> headFoo.get(Map("foo" -> List(42)))
res0: Option[Int] = Some(42)
scala> headFoo.get(Map("foo" -> Nil))
res1: Option[Nothing] = None
scala> headFoo.get(Map("bar" -> List(13)))
res2: Option[Int] = None
请注意,这是Scalaz 7。
Note that this is Scalaz 7.
如果要组合的镜头不部分,可以使用〜
:
If the lens you want to compose isn't partial, you can make it so with ~
:
scala> def firstFoo[A, B] = ~Lens.firstLens[A, B] compose mapVPLens("foo")
firstFoo: [A, B]=> scalaz.PLensFamily[Map[String,(A, B)],Map[String,(A, B)],A,A]
scala> firstFoo.get(Map("foo" -> (42, 'a)))
res6: Option[Int] = Some(42)
如果您不喜欢一元运算符,还有一个 .partial
方法。
There's also a .partial
method if you don't like the unary operator.
这篇关于Scalaz:如何组合一个价值镜头的地图镜头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!