Teach Yourself some Functional Programming with Scala
-
Upload
damian-jureczko -
Category
Software
-
view
57 -
download
1
Transcript of Teach Yourself some Functional Programming with Scala
Imperative example ✗List<User> users = new ArrayList<>(); users.add(new User("John", 35)); users.add(new User("Michael", 27));
int count = 0;
for (User user : users) { if (user.getAge() > 30) { count += 1; }}
Functional example ✓val users = List(User("John", 35), User("Michael", 27))
val count = users.count(user => user.age > 30)
Referential transparency“An expression is said to be referentiallytransparent if it can be replaced with itscorresponding value without changing
the program's behavior.“
Result can be different for same arguments ✗def crazyInc(x: Int): Int = x + Random.nextInt()
val whoKnows = crazyInc(1)
Function without side effects
Result: x = 8
def add(x: Int, y: Int): Int = x + y
val x = add(1, 1) * add(2, 2)
Function with side effects
Result: x = 8, totalSum = 6
var totalSum = 0
def weirdAdd(x: Int, y: Int): Int = { val sum = x + y totalSum += sum sum}
val x = weirdAdd(1, 1) * weirdAdd(2, 2)
Functional ProgrammingWhat are the benefits?
compositionality (divide & conquer, generalize, reuse)code easier to reason aboutcode easier to parallelizecode easier to optimize (memoization)code easier to test
First-class functionsWe can use functions like we use other types
assign to variablepass to function (as argument)return from function
Assigning function to variableval inc: Int => Int = x => x + 1
val inc: Transformation = x => x + 1
val two = inc(1)
Passing function to high-order functionval count = users.count(user => user.age > 30)
def count(p: User ⇒ Boolean): Int
Returning function from high-order functiondef makeUserFilterByAge(threshold: Int): User => Boolean = user => user.age > threshold
val userOlderThen30: User => Boolean = makeUserFilterByAge(30)
val count = users.count(userOlderThen30)
SummaryFunctional programming is hereIt simplifies your lifeIt makes you a better developerScala is a good way to start