Why don't Scala Lists have an Ordering?

前端 未结 6 1578
攒了一身酷
攒了一身酷 2020-12-31 00:47

Is there a reason why there is no implicit Ordering for Lists in Scala?

val lists = List(List(2, 3, 1), List(2, 1, 3))
lists.sorted

error: could not find im         


        
6条回答
  •  傲寒
    傲寒 (楼主)
    2020-12-31 01:11

    The only really sensible total order over the class of List[Int] would be lexicographic (i.e, compare the first elements of the list, then the second if they are equal, the third if the seconds are equal, etc.). This isn't provided by the standard library, probably because there aren't that many cases where it's actually needed. It would be easy enough to create an implicit conversion from List[X] to Ordering[List[X]] that would implement that, and then you could simply import that conversion wherever you needed it.

提交回复
热议问题