Skip to content

Instantly share code, notes, and snippets.

@danclien
Last active August 29, 2015 14:00
Show Gist options
  • Save danclien/11239811 to your computer and use it in GitHub Desktop.
Save danclien/11239811 to your computer and use it in GitHub Desktop.
// Runs in a SBT console with scalaz references in Build.sbt
import scalaz._, Scalaz._
case class Person(age: Int, name: String)
object PeopleSort {
def sort(people: List[Person], fields: List[String]): List[Person] = {
val ordering = getScalaOrdering(fields)
people.sorted(ordering)
}
def getScalaOrdering(fields: List[String]) = {
// Converts the List[String] to a List[scalaz.Order]
val orders = fields.map(s => sorts(s))
// Reduces all the `Order`s into a single `Order` and converts to a `scala.Ordering`
Foldable[List].fold(orders).toScalaOrdering
}
val sorts = Map(
"age" -> Order.orderBy[Person, Int](_.age),
"name" -> Order.orderBy[Person, String](_.name)
)
}
/* Example */
val people = List(
Person(50, "Zack"),
Person(50, "Jane"),
Person(50, "Bob"),
Person(40, "Yasmine")
)
PeopleSort.sort(people, List("age")) // List(Person(40,Yasmine), Person(50,Zack), Person(50,Jane), Person(50,Bob))
PeopleSort.sort(people, List("name")) // List(Person(50,Bob), Person(50,Jane), Person(40,Yasmine), Person(50,Zack))
PeopleSort.sort(people, List("age", "name")) // List(Person(40,Yasmine), Person(50,Bob), Person(50,Jane), Person(50,Zack))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment