Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Inspired by Ben Lings' answer, I wrote my own version of <code>sort</code>:</p> <pre><code>def sort[A : Ordering](coll: Seq[Iterable[A]]) = coll.sorted </code></pre> <p>which is equivalent to:</p> <pre><code>def sort[A](coll: Seq[Iterable[A]])(implicit ordering: Ordering[A]) = coll.sorted </code></pre> <p>Note that <code>ordering</code> is implicitly converted to <code>Ordering[Iterable[A]]</code>.</p> <p>Examples:</p> <pre><code>scala&gt; def sort[A](coll: Seq[Iterable[A]])(implicit ordering: Ordering[A]) = coll.sorted sort: [A](coll: Seq[Iterable[A]])(implicit ordering: Ordering[A])Seq[Iterable[A]] scala&gt; val coll = List(List(1, 3), List(1, 2), List(0), Nil, List(2)) coll: List[List[Int]] = List(List(1, 3), List(1, 2), List(0), List(), List(2)) scala&gt; sort(coll) res1: Seq[Iterable[Int]] = List(List(), List(0), List(1, 2), List(1, 3), List(2)) </code></pre> <p>It was asked how to supply your own comparison function; It suffices to use Ordering.fromLessThan:</p> <pre><code>scala&gt; sort(coll)(Ordering.fromLessThan(_ &gt; _)) res4: Seq[Iterable[Int]] = List(List(), List(2), List(1, 3), List(1, 2), List(0)) </code></pre> <p><code>Ordering.by</code> allows you to map your value into another type for which there is already an Ordering instance. Given that also tuples are ordered, this can be useful for lexicographical comparison of case classes.</p> <p>To make an example, let's define a wrapper of an Int, apply <code>Ordering.by(_.v)</code>, where <code>_.v</code> extracts the underlying value, and show that we obtain the same result:</p> <pre><code>scala&gt; case class Wrap(v: Int) defined class Wrap scala&gt; val coll2 = coll.map(_.map(Wrap(_))) coll2: List[List[Wrap]] = List(List(Wrap(1), Wrap(3)), List(Wrap(1), Wrap(2)), List(Wrap(0)), List(), List(Wrap(2))) scala&gt; sort(coll2)(Ordering.by(_.v)) res6: Seq[Iterable[Wrap]] = List(List(), List(Wrap(0)), List(Wrap(1), Wrap(2)), List(Wrap(1), Wrap(3)), List(Wrap(2))) </code></pre> <p>Finally, let's do the same thing on a case class with more members, reusing the comparators for Tuples:</p> <pre><code>scala&gt; case class MyPair(a: Int, b: Int) defined class MyPair scala&gt; val coll3 = coll.map(_.map(MyPair(_, 0))) coll3: List[List[MyPair]] = List(List(MyPair(1,0), MyPair(3,0)), List(MyPair(1,0), MyPair(2,0)), List(MyPair(0,0)), List(), List(MyPair(2,0))) scala&gt; sort(coll3)(Ordering.by(x =&gt; (x.a, x.b))) res7: Seq[Iterable[MyPair]] = List(List(), List(MyPair(0,0)), List(MyPair(1,0), MyPair(2,0)), List(MyPair(1,0), MyPair(3,0)), List(MyPair(2,0))) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload