在 Scala 中使用通用更新功能在其部件上实现产品类型

Implement product type in Scala with generic update function working on its parts

在 Scala 中,我需要创建一个表示复合值的产品类型 &,例如:

val and: String & Int & User & ... = ???

and 应该有一个 String 部分和一个 Int 部分和一个 User 部分。这类似于 Scala with 关键字:

val and: String with Int with User with ... = ???

有了这样的产品类型,我需要一种方法,有一个函数 A => A,将其应用于某些产品价值,并在更改 A 部分后取回该产品。这意味着产品中的每种类型都必须是唯一的 - 这是可以接受的。

一个重要的限制是,当对产品应用函数 A => A 时,我只知道产品内部某处有 A 但不知道它包含的其他类型的信息。但是作为函数的调用者,我向它传递了一个具有完整类型信息的产品,并希望将此完整类型作为函数签名的一部分返回。

在伪代码中:

def update[A, Rest](product: A & Rest, f: A => A): A & Rest

使用 Shapeless 或其他深奥的东西对我来说没问题。我尝试使用 HLists 但它们是有序的,而像异构集这样的东西在这里更适合代表 A & Rest 部分。

更新:

这是解决我的用例的代码,该代码取自下面的 Régis Jean-Gilles 回答,添加了读取支持、一些评论和改进的类型安全性:

object product {

  /** Product of `left` and `right` values. */
  case class &[L, R](left: L, right: R)

  implicit class AndPimp[L](val left: L) extends AnyVal {
    /** Make a product of `this` (as left) and `right`. */
    def &[R](right: R): L & R = new &(left, right)
  }

  /* Updater. */

  /** Product updater able to update value of type `A`. */
  trait ProductUpdater[P, A] {
    /** Update product value of type `A`.
      * @return updated product */
    def update(product: P, f: A ⇒ A): P
  }

  trait LowPriorityProductUpdater {
    /** Non-product value updater. */
    implicit def valueUpdater[A]: ProductUpdater[A, A] = new ProductUpdater[A, A] {
      override def update(product: A, f: A ⇒ A): A = f(product)
    }
  }

  object ProductUpdater extends LowPriorityProductUpdater {
    /** Left-biased product value updater. */
    implicit def leftProductUpdater[L, R, A](implicit leftUpdater: ProductUpdater[L, A]): ProductUpdater[L & R, A] =
      new ProductUpdater[L & R, A] {
        override def update(product: L & R, f: A ⇒ A): L & R =
          leftUpdater.update(product.left, f) & product.right
      }

    /** Right-biased product value updater. */
    implicit def rightProductUpdater[L, R, A](implicit rightUpdater: ProductUpdater[R, A]): ProductUpdater[L & R, A] =
      new ProductUpdater[L & R, A] {
        override def update(product: L & R, f: A ⇒ A): L & R =
          product.left & rightUpdater.update(product.right, f)
      }
  }

  /** Update product value of type `A` with function `f`.
    * Won't compile if product contains multiple `A` values.
    * @return updated product */
  def update[P, A](product: P)(f: A ⇒ A)(implicit updater: ProductUpdater[P, A]): P =
    updater.update(product, f)

  /* Reader. */

  /** Product reader able to read value of type `A`. */
  trait ProductReader[P, A] {
    /** Read product value of type `A`. */
    def read(product: P): A
  }

  trait LowPriorityProductReader {
    /** Non-product value reader. */
    implicit def valueReader[A]: ProductReader[A, A] = new ProductReader[A, A] {
      override def read(product: A): A = product
    }
  }

  object ProductReader extends LowPriorityProductReader {
    /** Left-biased product value reader. */
    implicit def leftProductReader[L, R, A](implicit leftReader: ProductReader[L, A]): ProductReader[L & R, A] =
      new ProductReader[L & R, A] {
        override def read(product: L & R): A =
          leftReader.read(product.left)
      }

    /** Right-biased product value reader. */
    implicit def rightProductReader[L, R, A](implicit rightReader: ProductReader[R, A]): ProductReader[L & R, A] =
      new ProductReader[L & R, A] {
        override def read(product: L & R): A =
          rightReader.read(product.right)
      }
  }

  /** Read product value of type `A`.
    * Won't compile if product contains multiple `A` values.
    * @return value of type `A` */
  def read[P, A](product: P)(implicit productReader: ProductReader[P, A]): A =
    productReader.read(product)

  // let's test it

  val p = 1 & 2.0 & "three"

  read[Int & Double & String, Int](p) // 1
  read[Int & Double & String, Double](p) // 2.0
  read[Int & Double & String, String](p) // three

  update[Int & Double & String, Int](p)(_ * 2) // 2 & 2.0 & three
  update[Int & Double & String, Double](p)(_ * 2) // 1 & 4.0 & three
  update[Int & Double & String, String](p)(_ * 2) // 1 & 2.0 & threethree

}

作为一个简单的想法,您可以这样做:

scala> case class And[A, B](first: A, second: B)
defined class And

scala> val x:  String And Double And Int = And(And("test", 1.1), 10)
x: And[And[String,Double],Int] = And(And(test,1.1),10)

scala> x.copy(second = 100)
res0: And[And[String,Double],Int] = And(And(test,1.1),100)

当然可以用这样的产品定义函数:

def update(product: String And Int, f: String => String): String And Int

不是最佳变体,在我看来@TravisBrown 或@MilesSabin 可以提供更完整的答案。

在示例中我们将使用 shapeless 2.2.5。 所以我们可以将必要的类型表示为 HList (没有数量问题)。由于它是 HList,因此可以应用 Poly 函数:

trait A
def aFunc(a: A) = a

trait lowPriority extends Poly1 {
  implicit def default[T] = at[T](poly.identity)
}

object polyApplyToTypeA extends lowPriority {
  implicit def caseA = at[A](aFunc(_))
}

list.map(polyApplyToTypeA) //> applies only to type A

这是第一种方法,使用它我们应该只使用特殊的Poly函数(可以生成它们),实际上,这是一个问题。

第二种方法是自己定义一个函数,逻辑有点难:

def applyToType[L <: HList, P <: HList, PO <: HList, S <: HList, F]
(fun: F => F, l: L)
(implicit partition: Partition.Aux[L, F, P, S],
                 tt: ToTraversable.Aux[P, List, F],
                 ft: FromTraversable[P],
                  p: Prepend.Aux[S, P, PO],
                  a: Align[PO, L]): L = 
(l.filterNot[F] ::: l.filter[F].toList[F].map(fun).toHList[P].get).align[L]

此函数按类型过滤 HList,将其转换为 List,应用我们的函数,并将其转换回 HList,还对齐类型,以免更改 HList 类型对齐方式。按预期工作。完整示例在这里:https://gist.github.com/pomadchin/bf46e21cb180c2a81664

这是一个仅使用纯 scala 且不需要库的解决方案。它依赖于使用相当标准方法的类型 class:

scala> :paste
// Entering paste mode (ctrl-D to finish)
case class &[L,R](left: L, right: R)
implicit class AndOp[L](val left: L) {
  def &[R](right: R): L & R = new &(left, right)
}

trait ProductUpdater[P,A] {
  def apply(p: P, f: A => A): P
}
trait LowPriorityProductUpdater {
  implicit def noopValueUpdater[P,A]: ProductUpdater[P,A] = {
    new ProductUpdater[P,A] {
      def apply(p: P, f: A => A): P = p // keep as is
    }
  }
}
object ProductUpdater extends LowPriorityProductUpdater {
  implicit def simpleValueUpdater[A]: ProductUpdater[A,A] = {
    new ProductUpdater[A,A] {
      def apply(p: A, f: A => A): A = f(p)
    }
  }
  implicit def productUpdater[L, R, A](
    implicit leftUpdater: ProductUpdater[L, A], rightUpdater: ProductUpdater[R, A]
  ): ProductUpdater[L & R, A] = {
    new ProductUpdater[L & R, A] {
      def apply(p: L & R, f: A => A): L & R = &(leftUpdater(p.left, f), rightUpdater(p.right, f))
    }
  }
}
def update[A,P](product: P)(f: A => A)(implicit updater: ProductUpdater[P,A]): P = updater(product, f)
// Exiting paste mode, now interpreting.

我们来测试一下:

scala> case class User(name: String, age: Int)
defined class User

scala> val p: String & Int & User & String = "hello" & 123 & User("Elwood", 25) & "bye"
p: &[&[&[String,Int],User],String] = &(&(&(hello,123),User(Elwood,25)),bye)

scala> update(p){ i: Int => i + 1 }
res0: &[&[&[String,Int],User],String] = &(&(&(hello,124),User(Elwood,25)),bye)

scala> update(p){ s: String => s.toUpperCase }
res1: &[&[&[String,Int],User],String] = &(&(&(HELLO,123),User(Elwood,25)),BYE)

scala> update(p){ user: User =>
     |   user.copy(name = user.name.toUpperCase, age = user.age*2)
     | }
res2: &[&[&[String,Int],User],String] = &(&(&(hello,123),User(ELWOOD,50)),bye)

更新: 回应:

Is it possible to make this not compile when a product doesn't contain a value to update

是的,这绝对有可能。我们可以更改 ProductUpdater 类型 class 但在这种情况下,我发现引入单独的类型 class ProductContainsType 作为给定产品的证据要容易得多 P 包含至少一个 A:

类型的元素
scala> :paste
// Entering paste mode (ctrl-D to finish)

@annotation.implicitNotFound("Product ${P} does not contain type ${A}")
abstract sealed class ProductContainsType[P,A]
trait LowPriorityProductContainsType {
  implicit def compositeProductContainsTypeInRightPart[L, R, A](
    implicit rightContainsType: ProductContainsType[R, A]
  ): ProductContainsType[L & R, A] = null
}
object ProductContainsType extends LowPriorityProductContainsType {
  implicit def simpleProductContainsType[A]: ProductContainsType[A,A] = null
  implicit def compositeProductContainsTypeInLeftPart[L, R, A](
    implicit leftContainsType: ProductContainsType[L, A]
  ): ProductContainsType[L & R, A] = null
}
// Exiting paste mode, now interpreting.

现在我们可以定义更严格的 update 方法:

def strictUpdate[A,P](product: P)(f: A => A)(
  implicit 
    updater: ProductUpdater[P,A], 
    containsType: ProductContainsType[P,A]
): P = updater(product, f)

让我们看看:

scala> strictUpdate(p){ s: String => s.toUpperCase }
res21: &[&[&[String,Int],User],String] = &(&(&(HELLO,123),User(Elwood,25)),BYE)

scala> strictUpdate(p){ s: Symbol => Symbol(s.name.toUpperCase) }
<console>:19: error: Product &[&[&[String,Int],User],String] does not contain type Symbol
              strictUpdate(p){ s: Symbol => Symbol(s.name.toUpperCase) }