Based on:
import shapeless._ case class Content(field: Int) lens[Content] >> 'field
I am trying to make a lens-creating method, something along:
def makeLens[T <: Product](s: Symbol) = lens[T] >> s
But it seems non-obvious. Is it possible to do?
If not, the end result I'm trying to achieve is a generic method for updating nested Maps with case-class contents, e.g.:
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)
I cannot get it to work when parameterized by T and f. Are there any other idiomatic boilerplate-free solutions?
Thanks!
The problem with your makeLens
is that we want e.g. makeLens[Content]('foo)
to fail at compile time, and that's not possible with an ordinary Symbol
argument. You need some extra implicit arguments to track the singleton type for the given name and to provide evidence that it's the name of a member of the case class:
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]
And then:
scala> case class Content(field: Int) defined class Content scala> makeLens[Content]('field) res0: shapeless.Lens[Content,Int] = shapeless.Lens$$anon$6@7d7ec2b0
But makeLens[Content]('foo)
won't compile (which is what we want).
You need the same kind of tracking for your 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)