无形状2.0.0镜头是否可以与列表/集合一起使用?(Does Shapeless 2.0.0 lens work with Lists/collections?)

编程入门 行业动态 更新时间:2024-10-22 22:48:39
形状2.0.0镜头是否可以与列表/集合一起使用?(Does Shapeless 2.0.0 lens work with Lists/collections?)

如果我有这个:

case class Foo( age: Int, name: String, bar: List[Bar], alive: Boolean ) case class Bar( hey: String, you: String )

我可以创建一个可以获取/设置foo.bar(1).you的镜头吗?

If I have this:

case class Foo( age: Int, name: String, bar: List[Bar], alive: Boolean ) case class Bar( hey: String, you: String )

Can I create a lens that can get/set foo.bar(1).you?

最满意答案

不是开箱即用,而且您确实需要一个部分镜头,以负责任的方式通过索引在列表中进行查找。 尽管如此,Scalaz提供了您所需要的功能,而无形化contrib使互操作性变得轻松:

import scalaz.PLens._ import shapeless.lens import shapeless.contrib.scalaz._ val secondBar = (lens[Foo] >> 'bar).asScalaz.partial.andThen(listNthPLens(1))

接着:

scala> secondBar.get(fooB) res0: Option[Bar] = None scala> secondBar.get(fooA) res1: Option[Bar] = Some(Bar(foo,bar)) scala> secondBar.set(fooA, Bar("bar", "foo")) res2: Option[Foo] = Some(Foo(1,,List(Bar(,), Bar(bar,foo)),false)) scala> secondBar.set(fooB, Bar("bar", "foo")) res3: Option[Foo] = None

如果你不介意过着危险的生活,你也可以编写自己的无形镜头来查找列表中的位置(类型为Lens[List[A], A] ),但这会放弃很多无形和镜片的价值。

Not out of the box, and you really need a partial lens to look things up in a list by index responsibly. Scalaz provides what you need, though, and shapeless-contrib makes interoperability easy:

import scalaz.PLens._ import shapeless.lens import shapeless.contrib.scalaz._ val secondBar = (lens[Foo] >> 'bar).asScalaz.partial.andThen(listNthPLens(1))

And then:

scala> secondBar.get(fooB) res0: Option[Bar] = None scala> secondBar.get(fooA) res1: Option[Bar] = Some(Bar(foo,bar)) scala> secondBar.set(fooA, Bar("bar", "foo")) res2: Option[Foo] = Some(Foo(1,,List(Bar(,), Bar(bar,foo)),false)) scala> secondBar.set(fooB, Bar("bar", "foo")) res3: Option[Foo] = None

If you don't mind living dangerously, you could also write your own Shapeless lens for looking up locations in a list (with a type like Lens[List[A], A]), but that would be giving up a lot of the value of both Shapeless and lenses.

更多推荐

本文发布于:2023-07-04 11:04:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1023583.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:形状   镜头   列表   Shapeless   work

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!