Sure! Let’s create a Scala program that models a school system. This program will include:
- Tail Recursion: To process lists efficiently.
- Algebraic Data Types (ADT): To define
Student, Grade, and other related types.
- Modules: Demonstrating different ways to import modules.
- Method Overloading: To provide multiple ways to add grades.
- Singleton Object: Acting as the main entry point and managing the school data.
Overview
Our program will consist of the following components:
- Data Models (ADT): Define the core data structures.
- Utility Module: Provide helper functions, utilizing tail recursion.
- School Module: Manage students and their grades with overloaded methods.
- Main Singleton Object: Bring everything together and demonstrate functionality.
1. Data Models (ADT)
First, we’ll define the necessary data models using sealed traits and case classes to create ADTs.
// File: Models.scala
package school.models
sealed trait Gender
case object Male extends Gender
case object Female extends Gender
case object Other extends Gender
sealed trait Subject
case object Mathematics extends Subject
case object Science extends Subject
case object Literature extends Subject
case object History extends Subject
case object Art extends Subject
case class Grade(subject: Subject, score: Int)
case class Student(
id: Int,
name: String,
gender: Gender,
grades: List[Grade]
)
2. Utility Module with Tail Recursion
Next, we create a utility module that includes a tail-recursive function to calculate the average grade for a student.
// File: Utils.scala
package school.utils
import school.models.Grade
object Utils {
// Tail-recursive function to calculate total score
def totalScore(grades: List[Grade]): Int = {
@annotation.tailrec
def helper(gradesList: List[Grade], acc: Int): Int = gradesList match {
case Nil => acc
case head :: tail => helper(tail, acc + head.score)
}
helper(grades, 0)
}
// Function to calculate average score
def averageScore(grades: List[Grade]): Double = {
if (grades.isEmpty) 0.0
else totalScore(grades).toDouble / grades.length
}
}
3. School Module with Method Overloading
Now, we build the School module to manage students. We will demonstrate method overloading by providing different ways to add a grade to a student.
// File: School.scala
package school
import school.models._
import school.utils.Utils
object School {
private var students: List[Student] = List()
// Add a new student
def addStudent(student: Student): Unit = {
students = student :: students
}
// Overloaded method to add a grade by providing Student ID and Grade
def addGrade(studentId: Int, grade: Grade): Unit = {
students = students.map { student =>
if (student.id == studentId)
student.copy(grades = grade :: student.grades)
else
student
}
}
// Overloaded method to add a grade by providing Student ID, Subject, and Score
def addGrade(studentId: Int, subject: Subject, score: Int): Unit = {
val grade = Grade(subject, score)
addGrade(studentId, grade)
}
// Get a student by ID
def getStudent(id: Int): Option[Student] = {
students.find(_.id == id)
}
// Calculate average score for a student
def getAverageScore(id: Int): Double = {
getStudent(id) match {
case Some(student) => Utils.averageScore(student.grades)
case None => 0.0
}
}
// List all students
def listStudents(): List[Student] = students
}
4. Main Singleton Object
Finally, we create a Main object that serves as the entry point of the program. It demonstrates importing modules in different ways, using overloaded methods, and utilizing the ADTs and tail recursion.
// File: Main.scala
package school.main
// Importing the entire School module
import school.School
// Importing specific functions from Utils and using an alias
import school.utils.{averageScore => avgScore}
// Importing all models with an alias
import school.models.{Student, Gender, Subject, Grade}
object Main extends App {
// Create some students
val student1 = Student(1, "Alice", Female, List())
val student2 = Student(2, "Bob", Male, List())
val student3 = Student(3, "Charlie", Other, List())
// Add students to the school
School.addStudent(student1)
School.addStudent(student2)
School.addStudent(student3)
// Add grades using overloaded methods
School.addGrade(1, Grade(Mathematics, 85))
School.addGrade(1, Science, 90)
School.addGrade(2, Literature, 78)
School.addGrade(3, History, 88)
School.addGrade(3, Art, 95)
// Display all students and their average scores
for (student <- School.listStudents()) {
println(s"Student: ${student.name}, Gender: ${student.gender}")
println(s"Average Score: ${School.getAverageScore(student.id)}")
println("Grades:")
for (grade <- student.grades) {
println(s" Subject: ${grade.subject}, Score: ${grade.score}")
}
println("-----------------------------------")
}
// Example usage of imported alias
val aliceAvg = avgScore(School.getStudent(1).get.grades)
println(s"Alice's Average Score (using imported alias): $aliceAvg")
}
Putting It All Together
To run the program, ensure that the files are organized according to their package structure. Here's a simplified view:
src/
└─ school/
├─ models/
│ └─ Models.scala
├─ utils/
│ └─ Utils.scala
├─ School.scala
└─ main/
└─ Main.scala
Compile and run the Main object. You should see output similar to:
Student: Charlie, Gender: Other
Average Score: 91.5
Grades:
Subject: Art, Score: 95
Subject: History, Score: 88
-----------------------------------
Student: Bob, Gender: Male
Average Score: 78.0
Grades:
Subject: Literature, Score: 78
-----------------------------------
Student: Alice, Gender: Female
Average Score: 87.5
Grades:
Subject: Science, Score: 90
Subject: Mathematics, Score: 85
-----------------------------------
Alice's Average Score (using imported alias): 87.5
Explanation of Concepts Used
-
Tail Recursion: In Utils.totalScore, the recursive helper function accumulates the total score efficiently without growing the call stack.
-
Algebraic Data Types (ADT):
Gender, Subject are sealed traits with case objects representing specific instances.
Grade and Student are case classes modeling the data.
-
Modules and Imports:
School is an object acting as a module managing students.
- In
Main, different import strategies are demonstrated:
- Importing the entire
School module.
- Importing specific functions with an alias (
averageScore as avgScore).
- Importing specific models with their respective names.
-
Method Overloading:
addGrade in the School object is overloaded to accept either a Grade object or separate Subject and Score parameters.
-
Singleton Object:
School and Main are singleton objects, ensuring a single instance managing school data and serving as the program's entry point, respectively.
This program effectively demonstrates the required Scala concepts within a cohesive application model. You can expand upon this foundation by adding more functionalities, such as removing students, updating grades, or handling different types of assessments.