在Scala中,为什么字符串有序但Seq [Char]没有?

时间:2019-08-14 18:02:30

标签: scala sorting

它们几乎是同一件事。是的,只能编译下面的第一个代码:

排序字符串:

val ss = Seq(
  "abc",
  "def"
)

ss.sorted

排序后的序列:

val ss = Seq(
  "abc",
  "def"
)
.map(_.toSeq)

ss.sorted

这样的设计有什么意义?

2 个答案:

答案 0 :(得分:2)

您需要添加

import scala.math.Ordering.Implicits._

(或scala.math.Ordering.Implicits.seqOrdering)。

文档中为什么需要这种额外的导入:

  

Not in the standard scope due to the potential for divergence: For instance implicitly[Ordering[Any]] diverges in its presence.

答案 1 :(得分:1)

我认为StringSeq[Char]是同构的,但不相同。它们与Int(Byte, Byte, Byte, Byte)相同。 String具有其他语义。

如果添加Ordering[Seq[Char]],则拥有Ordering[A : Ordered]是一致的。而且看来它应该放在stdlib中。

无论如何,这不是一个“设计”问题,因为没有什么可以阻止您自己编写Ordering[Seq[Char]]实例。