arc*_*ica 2 sorting functional-programming scala scala-collections
我有N个字段的简单课程。
case class Book(a: UUID... z: String)
Run Code Online (Sandbox Code Playgroud)
和功能:
def sort(books:Seq[Book], fields:Seq[SortingFields]) = {...}
Run Code Online (Sandbox Code Playgroud)
哪里
case class SortingField(field: String, asc: Boolean)
Run Code Online (Sandbox Code Playgroud)
其中field-Book类的字段,asc-排序方向。
因此,预先我不知道哪个字段(从0到N)和排序顺序会进入我的函数来对books集合进行排序。它可以是单个ID字段,也可以是特定顺序的类的所有存在字段。
如何实施?
我将为此使用现有Ordering特征,并使用一个从映射Book到字段的函数,即Ordering.by[Book, String](_.author)。然后,您可以简单地使用进行排序books.sorted(myOrdering)。如果我在Book的伴随对象上定义了一个辅助方法,则获得这些顺序非常简单:
object Book {
def by[A: Ordering](fun: Book => A): Ordering[Book] = Ordering.by(fun)
}
case class Book(author: String, title: String, year: Int)
val xs = Seq(Book("Deleuze" /* and Guattari */, "A Thousand Plateaus", 1980),
Book("Deleuze", "Difference and Repetition", 1968),
Book("Derrida", "Of Grammatology", 1967))
xs.sorted(Book.by(_.title)) // A Thousand, Difference, Of Grammatology
xs.sorted(Book.by(_.year )) // Of Grammatology, Difference, A Thousand
Run Code Online (Sandbox Code Playgroud)
然后,要按多个字段链接排序,您可以创建自定义排序,该排序将遍历这些字段,直到一个比较不为零。例如,我可以添加一个扩展方法andThen来Ordering像这样:
implicit class OrderingAndThen[A](private val self: Ordering[A]) extends AnyVal {
def andThen(that: Ordering[A]): Ordering[A] = new Ordering[A] {
def compare(x: A, y: A): Int = {
val a = self.compare(x, y)
if (a != 0) a else that.compare(x, y)
}
}
}
Run Code Online (Sandbox Code Playgroud)
所以我可以写:
val ayt = Book.by(_.author) andThen Book.by(_.year) andThen Book.by(_.title)
xs.sorted(ayt) // Difference, A Thousand, Of Grammatology
Run Code Online (Sandbox Code Playgroud)