case class Book(title: String, author: String, year: Int, category: String)
object EnhancedLibraryManagement extends App {
var library = List(
Book("1984", "George Orwell", 1949, "Dystopian"),
Book("To Kill a Mockingbird", "Harper Lee", 1960, "Fiction"),
Book("The Great Gatsby", "F. Scott Fitzgerald", 1925, "Classic"),
Book("Brave New World", "Aldous Huxley", 1932, "Dystopian"),
Book("Moby Dick", "Herman Melville", 1851, "Classic"),
Book("The Catcher in the Rye", "J.D. Salinger", 1951, "Fiction")
)
def addBook(library: List[Book], book: Book): List[Book] = {
book :: library
}
def searchBooks(library: List[Book], query: String): List[Book] = {
library.filter(book => book.title.contains(query) || book.author.contains(query))
}
def filterByCategory(library: List[Book], category: String): List[Book] = {
library.filter(_.category == category)
}
def totalBooks(library: List[Book]): Int = {
library.length
}
def averagePublicationYear(library: List[Book]): Double = {
if (library.isEmpty) 0.0
else library.map(_.year).sum.toDouble / library.length
}
def sortBooksByTitle(library: List[Book]): List[Book] = {
library.sortBy(_.title)
}
def sortBooksByYear(library: List[Book]): List[Book] = {
library.sortBy(_.year)
}
def groupBooksByCategory(library: List[Book]): Map[String, List[Book]] = {
library.groupBy(_.category)
}
def partitionBooksByYear(library: List[Book], year: Int): (List[Book], List[Book]) = {
library.partition(_.year < year)
}
def collectTitlesAfterYear(library: List[Book], year: Int): List[String] = {
library.collect {
case Book(title, _, y, _) if y > year => title
}
}
}