This document provides an introduction to functional programming and the Scala programming language. It discusses core concepts of functional programming like immutable data, pure functions, expressions over instructions, and first-class functions. It provides examples comparing imperative Java code to equivalent functional Scala code. The document also outlines benefits of functional programming like simpler concurrency, optimizations, easier debugging, and cleaner code. It concludes by providing additional resources for learning Scala and functional programming.
7. 7
Core Ideas
• Data is immutable
• PURE function are our basic building block
• Use expressions over instructions
• First class functions
• Type-strictness
9. 9
Benefits!
• Simpler concurrency/parallelism
• Optimizations with caching or memoization
• Easier debugging
• Cleaner/less verbose code
• Encourages code re-use
• Promotes Test Driven Development
10. 10
Pure vs Impure
// In Main.java
public String getFormal(String name) {
name = "Mr." + name;
return name;
}
// In Main.scala
def getFormal(name: String) = s"Mr. $name!"
11. 11
Expressions vs Instructions
// In Main.java
public double[] convertToMeters(double[] measurements) {
double[] metricMeasurements =
new double[measurements.length];
for(int i = 0; i < measurements.length; ++i) {
metricMeasurements[i] =
measurements[i] * CONVERSION_FACTOR;
}
return metricMeasurements;
}
// In Main.scala
def convertToMeters(measurements: Seq[Double]) =
measurements.map(n => n * CONVERSION_FACTOR)
17. 17
Type Strictness
sealed trait Person
case class Student(name: String) extends Person
case class Alumni(name: String) extends Person
def getBusFare(person : Person): Int = {
person match {
case p: Student => 0
case p: Alumni => 2
}
}
18. 18
Options
// Form asking for person's gender
// a) Female
// b) Male
// c) Don’t want to disclose
def main(args: Array[String]): Unit = {
val answers = Seq(Some("Female"), Some("Male"), Some(null), None)
answers.map(a => a match {
case Some(gender) =>
if(gender == null){
"the didn't want to disclose his or her gender"
} else {
s"The user's gender is $gender"
}
case None => "the user didn't pick a value on the form"
})
}