Skip to content

Instantly share code, notes, and snippets.

@SamsadSajid
Last active April 15, 2022 23:58
Show Gist options
  • Save SamsadSajid/7e7c2dc28c7ca5ac6f5053abed58cab0 to your computer and use it in GitHub Desktop.
Save SamsadSajid/7e7c2dc28c7ca5ac6f5053abed58cab0 to your computer and use it in GitHub Desktop.
Scala tut
// filtering alphanumeric with isLetterOrDigit
// convert a char to lower with toLower
val string: String = "A man, a plan, a canal: Panama"
string.toCharArray.filter(_.isLetterOrDigit).map(_.toLower)
// convert a string to lower case
string.toLowerCase()
// ========================================================================= //
// partial function demo with chaining //
// ========================================================================//
def calculateGradeE: PartialFunction[Double, String] = {
case mark: Double if mark >= 0 && mark < 30 => "E"
}
def calculateGradeD: PartialFunction[Double, String] = {
case mark: Double if mark >= 30 && mark < 45 => "D"
}
def calculateGradeC: PartialFunction[Double, String] = {
case mark: Double if mark >= 45 && mark < 60 => "C"
}
def calculateGradeBSchool1: PartialFunction[Double, String] = {
case mark: Double if mark >= 60 && mark < 80 => "B"
}
def calculateGradeBSchool2: PartialFunction[Double, String] = {
case mark: Double if mark >= 60 && mark < 85 => "B"
}
def calculateGradeASchool1: PartialFunction[Double, String] = {
case mark: Double if mark >= 80 => "A"
}
def calculateGradeASchool2: PartialFunction[Double, String] = {
case mark: Double if mark >= 85 => "A"
}
val calculateCommonGrade =
calculateGradeE orElse calculateGradeD orElse calculateGradeC
val calculateGradeForSchool1 =
calculateCommonGrade orElse calculateGradeBSchool1 orElse calculateGradeASchool1
val calculateGradeForSchool2 =
calculateCommonGrade orElse calculateGradeBSchool2 orElse calculateGradeASchool2
val school1Grade = List[Double](80, 20, 45, 69, 85)
val resultForSchool1 =
school1Grade.collect[String](calculateGradeForSchool1)
println(s"result for School1 is ${resultForSchool1}")
val school2Grade = List[Double](80, 20, 45, 69, 80)
val resultForSchool2 =
school2Grade.collect[String](calculateGradeForSchool2)
println(s"result for School2 ${resultForSchool2}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment