编写通用的Scala合并函数,无法为编译器排列类型 [英] Writing a generic Scala merge function, can't get types to line up for compiler

查看:61
本文介绍了编写通用的Scala合并函数,无法为编译器排列类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过Scala学习FP.我在对象上有一个函数,用于合并两个排序的集合并返回相同的类型.看起来像这样:

I'm trying to learn FP with Scala. I've got a function on an object to merge two sorted collections and return the same type. It looks like this:

@tailrec def merge[A, Repr <: Seq[A]](merged: Repr, l1: Repr, l2: Repr)(
  implicit ordering: Ordering[A]): Repr = {
if (l1.isEmpty) merged ++ l2
else if (l2.isEmpty) merged ++ l1
else {
  val l1Head: A = l1.head
  val l2Head = l2.head
  val orderVal = ordering.compare(l1Head, l2Head)
  if (orderVal <= 0) {
    val m2: Repr = l1Head +: merged
    merge[A, Repr](m2, l1.tail, l2)
  } else {
    merge[A, Repr](l2Head +: merged, l1, l2.tail)
  }
 }
}

这给了我编译器错误"Seq [A]类型的表达与预期的Repr类型不符

It's giving me the compiler error "Expression of type Seq[A] doesn't conform to the expected type Repr

推荐答案

尝试

@tailrec def merge[A, Repr](merged: Repr, l1: Repr, l2: Repr)(implicit
  ev: Repr => SeqLike[A, Repr],
  cbf: CanBuildFrom[Repr, A, Repr],
  ordering: Ordering[A]
): Repr = {
  if (l1.isEmpty) merged ++ l2
  else if (l2.isEmpty) merged ++ l1
  else {
    val l1Head: A = l1.head
    val l2Head = l2.head
    val orderVal = ordering.compare(l1Head, l2Head)
    if (orderVal <= 0) {
      val m2: Repr = l1Head +: merged
      merge[A, Repr](m2, l1.tail, l2)
    } else {
      merge[A, Repr](l2Head +: merged, l1, l2.tail)
    }
  }
}

这篇关于编写通用的Scala合并函数,无法为编译器排列类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆