我想在Labeled Generics上使用来自无形贡献(+ scalaz)的序列,但是首先我需要映射FieldTypes。

是否有可能在该示例中创建缺少的f函数?

object TestLabelledGeneric {

  import shapeless._

  import singleton._


  val a = "name" ->> Option("hello") :: "y" ->> Option(1) :: HNil

  val b = Option("name" ->> "hello") :: Option("y" ->> 1) :: HNil

  val f = ???

  val name = Witness('name); val age = Witness('age)

  def assertTypedEquals[A](expected: A, actual: A): Unit = assert(expected == actual)

  assertTypedEquals[b.type](b, a.map(f))


}

解决了,谢谢@ travis-brown!

这是在我的机器上可以使用的版本:
object TestLabelledGeneric {

  import shapeless._

  import singleton._

  val a = "name" ->> Option("hello") :: "y" ->> Option(1) :: HNil

  val b = Option("name" ->> "hello") :: Option("y" ->> 1) :: HNil

  import labelled.{ FieldType, field }

  object f extends Poly1 {
    implicit def kv[K, V]: Case.Aux[
      FieldType[K, Option[V]],
      Option[FieldType[K, V]]
      ] =
      at(_.map(field[K](_)))
  }

  // If I try to use Witness.`"name"`.T directly in Res, I have a "not accessible type" error
  val name = Witness.`"name"`
  val y = Witness.`"y"`
  type Res = Option[FieldType[name.T, String]] :: Option[FieldType[y.T ,Int]] :: HNil

  def assertTypedEquals[A](expected: A, actual: A): Unit = assert(expected == actual)

  assertTypedEquals[Res](b, a.map(f))
}

最佳答案

您想要将FieldType[K, Option[V]]转换为Option[FieldType[K, V]]FieldType[K, Option[V]]Option[V]的子类型,您可以使用VFieldType[K, V]转换为shapeless.labelled.field

然后,您可以将此操作放入Poly1中:

import shapeless._, labelled.{ FieldType, field }, syntax.singleton._

object f extends Poly1 {
  implicit def kv[K, V]: Case.Aux[
    FieldType[K, Option[V]],
    Option[FieldType[K, V]]
  ] =
    at(_.map(field[K](_)))
}

这不能完全满足您的需求,因为a.map(f)的类型不是b.type(这是b的单例类型)。但是,您可以确认它确实可以满足您的要求:
scala> type Res =
     |   Option[FieldType[Witness.`"name"`.T, String]] ::
     |   Option[FieldType[Witness.`"y"`.T, Int]] :: HNil
defined type alias Res

scala> assertTypedEquals[Res](b, a.map(f))

是的,他们是一样的。

10-06 11:15