加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 09:58:26 所属栏目:安全 来源:网络整理
导读:在 Scala中,我需要创建一个产品类型表示复合值,例如: val and: String Int User ... = ??? 即并且应该有一个String部分和一个Int部分以及一个User部分.这类似于Scala的关键字: val and: String with Int with User with ... = ??? 具有这样的产品类型我需
在 Scala中,我需要创建一个产品类型&表示复合值,例如:

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

即并且应该有一个String部分和一个Int部分以及一个User部分.这类似于Scala的关键字:

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

具有这样的产品类型我需要一种方法,具有功能A => A,将其应用于某些产品价值,并通过更改A部件来恢复该产品.这意味着产品中的每种类型都必须是唯一的 – 这是可以接受的.

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

在伪代码中:

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

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

更新:

以下代码解决了我从RégisJean-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,A](implicit rightUpdater: ProductUpdater[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,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,A](implicit rightReader: ProductReader[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而不需要库的解决方案.它依赖于使用相当标准方法的类型类:

scala> :paste
// Entering paste mode (ctrl-D to finish)
case class &[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,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,124),bye)

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

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

更新:回应:

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

是的,这绝对是可能的.我们可以改变ProductUpdatertype类,但在这种情况下,我发现引入一个单独的类型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,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,A](
    implicit leftContainsType: ProductContainsType[L,A] = null
}
// Exiting paste mode,now interpreting.

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

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

让我们来看看:

scala> strictUpdate(p){ s: String => s.toUpperCase }
res21: &[&[&[String,BYE)

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读