简体   繁体   English

如何在Scala中编写“通用”mergesort?

[英]How to write a 'generic' mergesort in Scala?

Here is what I have so far : 这是我到目前为止:

  def mergesort[T <: Ordered[T]](elements : List[T]) : List[T] = {
    def merge(first : List[T], second : List[T]) : List[T] = (first, second) match {
      case (Nil, _) => second
      case (_, Nil) => first
      case (x :: xs, y :: ys) => if (x < y) x :: merge(xs, second) else y :: merge(first, ys)
    }

    if (elements.isEmpty) Nil
    else {
      val length = elements.length
      val (firstHalf, secondHalf) = elements.splitAt(length/2)

      merge(mergesort(firstHalf), mergesort(secondHalf))
    }
  }

The problem I'm having is that this fails 我遇到的问题是失败了

mergesort(List(1, 3, 6, 3, 1, 0))

error: inferred type arguments [Int] do not conform to method mergesort's type parameter bounds [T <: Ordered[T]]
       mergesort(List(1, 3, 6, 3, 1, 0))
       ^

Is there any way to make this work for all types which are ordered? 是否有任何方法可以使所有类型的订单工作? I though Scala would have some sort of implicit conversion to a 'rich' integer type, which I assumed would have the Ordered trait. 我虽然Scala会有某种隐式转换为'rich'整数类型,我认为它会有Ordered特性。

What you need is a view bound def mergesort[T <% Ordered[T]] . 你需要的是一个视图绑定def mergesort[T <% Ordered[T]] See answers to this question: Generic method to return first of two values . 查看此问题的答案: 返回两个值中的第一个的通用方法

This will now complie but you have some bugs in your algorithm giving you a stackoverflow error in the splitAt line. 现在这将编译但你的算法中有一些错误,在splitAt行中给你一个stackoverflow错误。

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

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