简体   繁体   中英

Type constructor for subtracting HList types?

I am looking for a type contructor that can subtract one HList type with another.

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 :

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.

As a footnote, while RemoveAll is a type constructor, in this context it's more relevantly a type class. 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. I'd suggest looking at the role Aux plays in the RemoveAll type class as an example of this pattern.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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