首页 文章

Scala:迭代类型类对象

提问于
浏览
0

我在Scala程序中使用了几种外部数据类型 . 我的目标是使用类型类在这些数据类型上定义多态函数 . 问题是在Scala程序本身中,这些数据类型必须在某些点按顺序迭代,这些点我需要使用类型类中的多态函数 . 所以,例如,如果我们有

trait Show[A] {
  def show(a: A, b : String): String
}

object Show {

  def apply[A](implicit sh: Show[A]): Show[A] = sh

  def show[A: Show](a: A, b : String) = Show[A].show(a, b)

  implicit class ShowOps[A: Show](a: A) {
    def show(b : String) = Show[A].show(a, b)}


  implicit val blogCanShow: Show[Int] = new Show[Blog] {
    def show(blog: Blog, b : String): String = s"blog $blog" + b
}
  implicit val twitterCanShow: Show[String] = new Show[Twitter] {
    def show(twitter: Twitter, b : String): String = s"twitter $twitter" + b    }
}

然后我需要使用这样的数据类型:

for each data type:
  call show()
  business logic
  call another polymorphic function like show()
  more business logic
  etc...

我尝试使用Shapeless中的HLists,但无法弄清楚如何获得可重复的代码块来使用它 . 我想我需要在这里使用某种反射,但不知道从哪里开始 . 任何建议或帮助将非常感谢 .

1 回答

  • 2

    有关此问题的着名讨论,请参阅http://tpolecat.github.io/2015/04/29/f-bounds.html .

    底线(朝向帖子底部)是您想要类似于 Seq[(A,Show[A]) forSome {type A}] 的东西,因此您可以访问 A 及其 Show . 在没有运行时反射的情况下,没有必要存储 Show[A] ,但Rob显示了一个更优雅的技巧来包含该对:

    trait ∃[F[_]] {
      type A
      val a: A
      val fa: F[A]
    }
    object ∃ {
      def apply[F[_], A0](a0: A0)(implicit ev: F[A0]): ∃[F] =
        new ∃[F] {
          type A = A0
          val a = a0
          val fa = ev
        }
    }
    

    所以你可以申报

    val shows: List[∃[Show]] = ∃(myBlog) :: ∃(myTweet) :: Nil
    

    并迭代它,根据需要引用 afa .

    对我来说,这比 HList 解决方案更可取,因为虽然代码最初看起来有点不透明,但是通过在IDE中右键单击可以快速清除任何未来读者的困惑 .

相关问题