【问题标题】:How to obtain all possible members of a coproduct如何获得一个联产品的所有可能成员
【发布时间】:2021-03-17 12:00:35
【问题描述】:

我一直在尝试列出联产品类型的所有成员。这个answer 真的很接近我想要达到的目标:

sealed trait Traity
case object Foo  extends Traity
case class Bar() extends Traity
case class Baz() extends Traity

import shapeless._

class NameHelper[A] {
  def apply[C <: Coproduct, K <: HList]()(
    implicit
    gen: LabelledGeneric.Aux[A, C],
    keys: ops.union.Keys.Aux[C, K],
    toSet: ops.hlist.ToTraversable.Aux[K, Set, Symbol]): Set[String] = toSet(keys()).map(_.name)
}

def names[A] = new NameHelper[A]

names[Traity]()

预期输出:

res0: Set[String] = Set(Bar, Baz, Foo)

但我的源类型不是密封特性,它是原始无形的副产品。我尝试了以下方法,但无法编译:

type ISB = Int :+: String :+: Boolean :+: CNil

class NameHelper2[A <: Coproduct] {
  def apply[K <: HList]()(
    implicit
  keys: ops.union.Keys.Aux[A, K],
  toSet: ops.hlist.ToTraversable.Aux[K, Set, Symbol]): Set[String] = toSet(keys()).map(_.name)
}

def names2[A <: Coproduct] = new NameHelper2[A]

names2[ISB]()

结果是一个缺失的隐含值:

could not find implicit value for parameter keys: shapeless.ops.union.Keys.Aux[ISB,K]
names2[ISB]()

我想要的是可能的副产品成员:Set(Int, String, Boolean)

提前致谢。

【问题讨论】:

    标签: scala union shapeless


    【解决方案1】:

    它不是那么接近。在那里提取现有的键,在这里创建类型的文本表示。

    你可以的

    class NameHelper2[C <: Coproduct] {
      def apply[L <: HList, L1 <: HList]()(
        implicit
        toHList: ops.coproduct.ToHList.Aux[C, L],
        fillWith: ops.hlist.FillWith[nullPoly.type, L],
        mapper: ops.hlist.Mapper.Aux[typeablePoly.type, L, L1],
        toSet: ops.hlist.ToTraversable.Aux[L1, Set, String]): Set[String] = toSet(mapper(fillWith()))
    }
    
    object nullPoly extends Poly0 {
      implicit def cse[X]: Case0[X] = at(null.asInstanceOf[X])
    }
    
    object typeablePoly extends Poly1 {
      implicit def cse[X](implicit typeable: Typeable[X]): Case.Aux[X, String] = at(_ => typeable.describe)
    }
    

    【讨论】:

    • 谢谢。我是使用 shapeless 的新手 :) 就像一个魅力。
    猜你喜欢
    • 2014-09-03
    • 2017-12-09
    • 2021-08-12
    • 2022-01-18
    • 2011-12-11
    • 1970-01-01
    • 2011-12-08
    • 2022-12-22
    • 2012-01-24
    相关资源
    最近更新 更多