简体   繁体   English

用于减去HList类型的类型构造函数?

[英]Type constructor for subtracting HList types?

I am looking for a type contructor that can subtract one HList type with another. 我正在寻找一种可以将一种HList类型与另一种类型相减的类型构造器。

trait Subtract {
  type Aux[Full <: HList, ToSubract <: HList] = ???
}

object SubtractExample {
  type AList = ClassA :: ClassB :: HNil 
  type BList = ClassB :: HNil

  Subtract.Aux[AList, BList] == ClassA :: HNil
}

If such constructor doesn't exist, can someone point me to the direction in how to implement one? 如果这样的构造函数不存在,有人可以指出我的实现方向吗? Thanks! 谢谢!

If AList will always contain the elements of BList in order (but not necessarily contiguously), you can use RemoveAll : 如果AList将始终包含的元素BList为了(但不是一定是连续的),你可以使用RemoveAll

import shapeless._, ops.hlist.RemoveAll

trait ClassA; trait ClassB

type AList = ClassA :: ClassB :: HNil
type BList = ClassB :: HNil

val remover = RemoveAll[AList, BList]

remover(new ClassA {} :: new ClassB {} :: HNil)

This will return a tuple of the removed elements and the leftovers (which is what you want). 这将返回删除的元素和剩余的元组(这是您想要的)。

This works for your example case, and even if your requirements are slightly different, the RemoveAll implementation would be a good place to start. 这适用于您的示例案例,即使您的要求略有不同, RemoveAll实现也是一个不错的起点。

As a footnote, while RemoveAll is a type constructor, in this context it's more relevantly a type class. 作为一个脚注,尽管RemoveAll 类型构造函数,但在这种情况下,它更相关的是类型类。 It also doesn't really make sense to have a type class with no type parameters but an Aux (which would normally be defined in the companion object, not the type class itself) with two. 拥有一个没有类型参数而只有一个Aux (通常是在同伴对象中定义,而不是类型类本身)的类型类也没有任何意义,这实际上是没有意义的。 I'd suggest looking at the role Aux plays in the RemoveAll type class as an example of this pattern. 我建议看一下AuxRemoveAll类型类中扮演的角色,作为这种模式的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM