11

基于:

import shapeless._

case class Content(field: Int)
lens[Content] >> 'field

我正在尝试制作一种镜头制作方法,例如:

def makeLens[T <: Product](s: Symbol) = lens[T] >> s

但这似乎并不明显。有可能吗?

如果不是,我试图实现的最终结果是使用案例类内容更新嵌套 Maps 的通用方法,例如:

import scalaz._
import Scalaz._
import PLens._
import shapeless._
import shapeless.contrib.scalaz._

def nestedMapLens[R, T <: Product](outerKey: String, innerKey: Int, f: Symbol) =
  ~((lens[T] >> f).asScalaz) compose mapVPLens(innerKey) compose mapVPLens(outerKey)

当由 T 和 f 参数化时,我无法让它工作。还有其他惯用的无样板解决方案吗?

谢谢!

4

1 回答 1

12

您的问题makeLens是我们希望例如在编译时失败,而使用普通参数makeLens[Content]('foo)是不可能的。Symbol您需要一些额外的隐式参数来跟踪给定名称的单例类型并提供证据证明它是案例类成员的名称:

import shapeless._, ops.record.{ Selector, Updater }, record.FieldType

class MakeLens[T <: Product] {
  def apply[K, V, R <: HList](s: Witness.Aux[K])(implicit
    gen: LabelledGeneric.Aux[T, R],
    sel: Selector.Aux[R, K, V],
    upd: Updater.Aux[R, FieldType[K, V], R]
  ): Lens[T, V] = lens[T] >> s
}

def makeLens[T <: Product] = new MakeLens[T]

接着:

scala> case class Content(field: Int)
defined class Content

scala> makeLens[Content]('field)
res0: shapeless.Lens[Content,Int] = shapeless.Lens$$anon$6@7d7ec2b0

makeLens[Content]('foo)不会编译(这是我们想要的)。

您需要相同类型的跟踪nestedMapLens

import scalaz._, Scalaz._
import shapeless.contrib.scalaz._

case class LensesFor[T <: Product]() {
  def nestedMapLens[K, V, R <: HList](
    outerKey: String,
    innerKey: Int,
    s: Witness.Aux[K]
  )(implicit
    gen: LabelledGeneric.Aux[T, R],
    sel: Selector.Aux[R, K, V],
    upd: Updater.Aux[R, FieldType[K, V], R]
  ): PLens[Map[String, Map[Int, T]], V] =
    (lens[T] >> s).asScalaz.partial.compose(
      PLens.mapVPLens(innerKey)
    ).compose(
      PLens.mapVPLens(outerKey)
    )
}

请注意,我假设是build.sbt这样的:

scalaVersion := "2.11.2"

libraryDependencies ++= Seq(
  "com.chuusai" %% "shapeless" % "2.0.0",
  "org.typelevel" %% "shapeless-scalaz" % "0.3"
)

现在让我们定义一个示例地图和一些镜头:

val myMap = Map("foo" -> Map(1 -> Content(13)))

val myFoo1Lens = LensesFor[Content].nestedMapLens("foo", 1, 'field)
val myBar2Lens = LensesFor[Content].nestedMapLens("bar", 2, 'field)

接着:

scala> myFoo1Lens.get(myMap)
res4: Option[Int] = Some(13)

scala> myBar2Lens.get(myMap)
res5: Option[Int] = None

这与您将要获得的“无样板”差不多。凌乱的隐含参数列表起初令人生畏,但您很快就会习惯它们,并且经过一些练习后,它们在收集有关您正在使用的类型的不同证据方面的作用变得相当直观。

于 2014-10-04T00:34:44.520 回答