Why don't Scala Lists have an Ordering?

前端 未结 6 1624
攒了一身酷
攒了一身酷 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:19

    In newer Scala versions (tested with 2.12.5) there's an Ordering for Iterable[A]. Just ascribe the right type to your variable lists:

    scala> val lists = List(List(2, 3, 1), List(2, 1, 3))
    lists: List[List[Int]] = List(List(2, 3, 1), List(2, 1, 3))
    
    scala> (lists: List[Iterable[Int]]).sorted
    res0: List[Iterable[Int]] = List(List(2, 1, 3), List(2, 3, 1))
    

    Or convert the elements to instances of Iterable[] (which is a no-op for instances of List[]):

    scala> lists.map(_.toIterable).sorted
    res1: List[Iterable[Int]] = List(List(2, 1, 3), List(2, 3, 1))
    

提交回复
热议问题