2015-11-05 60 views
5

在斯卡拉通用更新功能的工作,我需要创建一个产品类型&代表一个复合值,例如:实现产品类型在斯卡拉在其部分

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

and应该有一个String部分和一个Int部分和User部分里面。这类似于斯卡拉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 

使用无形或其他深奥的东西是没有问题啊。我尝试使用HList s,但它们是有序的,而像异构集合这样的东西更适合于表示A & Rest部分。

UPDATE

这里是低于机智加入读取支持,一些评论认为,解决从雷吉斯让 - 吉尔的回答了我的使用情况下,代码和改进类型安全:

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 

} 
+1

关于'HList'是ordere D:这是无法修复的。虽然你可以定义方法/类型类来比较两种产品,并告诉你它们是否具有相同的类型,而不管顺序如何,但当谈到类型系统本身时,你是不幸的。你可以尝试所有的魔法,你永远不会让编译器认为'&[Int,String]'和'&[String,Int]'是一样的(这不足以实现一个完全接管的编译器插件类型检查这些类型,如果甚至可能的话)。 –

+0

@RégisJean-Gilles,明白了,谢谢。 – Tvaroh

回答

4

这里是一个解决方案,只使用纯scala没有所需的库。它使用一个相当标准的方法依赖于一个类型的类:

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) 

更新:回复:

是否有可能当产品不包含更新值时,不能编译

是的,这是绝对可能的。我们可以改变ProductUpdater型类,但在这种情况下,我觉得更容易引进一个单独的类型类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) } 
+0

如何为具有'A'和其他东西的产品编写类型?像'val pp:User&Any = p'或类似的例子。 – Tvaroh

+1

你不能写这样的类型,但是你可以要求一个证据(一个隐含的值),即一个产品类型至少有一个给定类型的元素。无论如何,我不确定它有多大的价值,因为在'update'中你想简单地忽略不是'A'类型的元素。我想你的意图是避免错误,如果你认为'update'会更新产品的至少一个元素,但它不是因为产品没有'A'类型的元素,那么你必须认识到它只会覆盖部分可能出现的错误:您可能还打算更新两个元素,但只有一个元素的类型为“A”。 –

+0

当产品不包含要更新的值时,是否可以使其不能编译? – Tvaroh

0

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

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 
3

不是一个最佳的变体,在我看来,@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

+0

第二种方法非常有趣(+1)。是否有可能推广到一个函数f:F => A'?然后在某些情况下,一个标准的单形函数可以做到,而不需要一个“Poly”。 –