Last active
November 21, 2015 08:59
-
-
Save sshark/95c8aca7f189807cfd8d to your computer and use it in GitHub Desktop.
Simple quicksort using various implementations to understand view bound, context bound and implicits
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // use Ordering for sorting | |
| def quicksort[A](l: Seq[A])(implicit ordering: Ordering[A]): Seq[A] = l match { | |
| case Nil => Nil | |
| case x :: xs => quicksort(xs.filter(ordering.compare(_, x) < 0)) ++ | |
| Seq(x) ++ | |
| quicksort(xs.filter(ordering.compare(_, x) >= 0)) | |
| } | |
| object DescOrdering extends Ordering[Int] { | |
| override def compare(x: Int, y: Int): Int = x - y match { | |
| case z if z < 0 => 1 | |
| case z if z > 0 => -1 | |
| case _ => 0 | |
| } | |
| } | |
| quicksort(Seq[Int]( 2, 1, 2, 3)) | |
| quicksort(Seq[Int]( 2, 2, 1, 3))(DescOrdering) | |
| // using Ordering context bound. This is a syntatic sugar which will be expanded to | |
| // quicksort(...) method. Context bound requires a parameterized type. In this case, | |
| // A: Ordering denotes Ordering[A] unlike [A <% String] view where A is coerced into | |
| // a String implicitly. | |
| def quicksortByContextBound[A: Ordering](l: Seq[A]): Seq[A] = { | |
| val ordering = implicitly[Ordering[A]] | |
| import ordering.mkOrderingOps // replaces gteq(...) and lt(...) methods with natural >= and < | |
| l match { | |
| case Nil => Nil | |
| case x :: xs => quicksortByContextBound(xs.filter(_ < x)) ++ | |
| Seq(x) ++ | |
| quicksortByContextBound(xs.filter(_ >= x)) | |
| } | |
| } | |
| quicksortByContextBound(Seq(2, 1, 2, 3))(DescOrdering) | |
| quicksortByContextBound(Seq('B', 'C', 'A')) // Seq of chars | |
| quicksortByContextBound(Seq("B", "C", "A")) // Seq of single letter strings | |
| // use Ordered, fixed order. | |
| def quicksortByOrdered[A](l: Seq[A])(implicit orderer: A => Ordered[A]): Seq[A] = l match { | |
| case Nil => Nil | |
| case x :: xs => quicksortByOrdered(xs.filter( _ < x)) ++ | |
| Seq(x) ++ | |
| quicksortByOrdered(xs.filter(_ >= x)) | |
| } | |
| quicksortByOrdered(Seq(2, 1, 3)) | |
| // use Ordered context view but it is deprecated, http://jatinpuri.com/2014/03/replace-view-bounds/ | |
| def quicksortByContextView[A <% Ordered[A]](l: Seq[A]): Seq[A] = l match { | |
| case Nil => Nil | |
| case x :: xs => quicksortByContextView(xs.filter( _ < x)) ++ | |
| Seq(x) ++ | |
| quicksortByContextView(xs.filter(_ >= x)) | |
| } | |
| quicksortByContextView(Seq(2, 1, 2, 3)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment