在 Scala 中使用通用更新函数在其部件上实现产品类型 [英] Implement product type in Scala with generic update function working on its parts

查看:41
本文介绍了在 Scala 中使用通用更新函数在其部件上实现产品类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Scala, I need to create a product type & that represents a compound value, e.g.:

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

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

I.e. and should have a String part and an Int part and a User parts inside. This is similar to Scala with keyword:

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

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

Having such product type I need a way to, having a function A => A, apply it to some product value and get that product back with A part altered. It implies that each type in product must be unique - that's acceptable.

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

One important limitation is that, when applying a function A => A to the product, I only know that the product has A somewhere inside but no information about other types it consists of. But as a caller of the function, I pass it a product with full type information and expect to get this full type back as part of function signature.

在伪代码中:

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

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

Using Shapeless or other esoteric stuff is okay for me. I tried using HLists but they are ordered, while something like heterogeneous set would be more appropriate here to represend A & Rest part.

更新:

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

Here is the code that solves my use case taken from Régis Jean-Gilles answer below wit added read support, some comments, and improved type-safety:

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 且不需要库的解决方案.它依赖于使用相当标准方法的类型类:

Here's a solution using only pure scala with no required library. It relies on a type class using a rather standard approach:

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 类型类,但在这种情况下,我发现引入一个单独的类型类 ProductContainsType 作为给定产品 P 至少包含一个 A 类型的元素:

Yes it is most definitely possible. We could alter the ProductUpdatertype class but in this case I find it much easier to introduce a separate type class ProductContainsType as an evidence that a given product P contains at least one element of type 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方法:

Now we can define our stricter update method:

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) }

这篇关于在 Scala 中使用通用更新函数在其部件上实现产品类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆