Functional
ProgramminginScala
inaNutshell
1
WhyScala?
2
JavaistooVerbose
// construct a empty list
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
// introduce a counting index, i
for (int i = 0; i<list.size(); i++) {
Integer element = list.get(i);
System.out.println(element);
}
3
ScalaisConcise
(1 :: 2 :: 3 :: Nil).foreach(println)
4
ElegantFunctionalProgrammingWay
val (openerO, wineO) = (Some(Opener), Some(Wine(vintage = 1997)))
val contentsO = for {
opener <- openerO
wine <- wineO
} yield opener.open(wine)
// contentsO: Option[Contents] = Some(contentsOfWine)
// no null, no NullPointerException
5
ElegantFunctionalProgrammingWay
val (openerO, wineO) = (Some(Opener), None)
val contentsO = for {
opener <- openerO
wine <- wineO
} yield opener.open(wine)
// contentsO: Option[Contents] = None
// no null, no NullPointerException
6
ScalasupportsOOP,too
// OOP polymorphism
val newOpener: Opener = new NormalOpener()
val oldOpener: Opener = new BrokenOpener()
val wine = new Wine()
println(newOpener.open(wine)) // contentsOfWine
println(oldOpener.open(wine)) // Exception occurs!
7
ScalaisCompatiblewithJava
Compatible with Hadoop and Spark
→ Official language for the bigdata community
// joda time based on java
import org.joda.time.DateTime, java.util.Date
val jodaDt: DateTime = new DateTime(new Date())
val month = month = dt.getMonthOfYear()
8
…andViceVersa
// scala code
object Person {
val MALE = "m";
}
// java code
public class App {
public static void main(String argv[]) {
Person$ person = Person$.MODULE$;
System.out.println(person.MALE());
}
}
9
WhatisFunctional
Programming?
10
ByDefinition,
A function is called pure if all its inputs are
declared as inputs - none of them are hidden -
and likewise all its outputs are declared as
outputs. 1
— Kris Jenkins
1
It is not a concrete definition but easy and intuitive.
11
Immutability
// value, not variable
val a = 1
a = 2 // error: reassignment to val
// list
val ints1: List[Int] = 1 :: 2 :: Nil
val ints2: List[Int] = ints1 :+ 3
println(ints1) // List(1, 2)
println(ints2) // List(1, 2, 3)
println(ints2 == 1 :: 2 :: 3 :: Nil) // true
12
Immutability
def fibonacci(n : Int): Int = {
// while loop requires temporary varables
var (a, b, i) = (0, 1, 0)
while( i < n ) {
val c = a + b
a = b
b = c
i = i + 1
}
return a
}
13
Immutability
// recursion doesn't requires temporary varables
def fibonacci(n : Int): Int = n match {
case 0 | 1 => n
case _ => fibonacci(n - 1) + fibonacci(n - 2)
}
14
SideEffect,byDefinition
A function is said to have a side effect if it
modifies some state outside its scope or has an
observable interaction with its calling functions
or the outside world.
— Side effect (computer science), Wikipedia
15
SideEffect
// this def has a side effect
def currentProgram(guide: TVGuide, channel: Int): Program = {
val schedule = guide.getSchedule(channel)
schedule.programAt(new Date())
}
16
SideEffect
// now it has no more side effects
// and it is immutable
def program(guide: TVGuide, channel: Int, date: Date): Program = {
val schedule = guide.getSchedule(channel)
schedule.programAt(date)
}
17
Let'sStartattheBeginningAgain…
A Program is functional iff it has no side effects.2
2
cf. Definition using Referential Transparency
18
WhyFunctional
Programming?
19
SoC:SeperationOfConcerns,ByDefinition
Soc is separating a computer program into
distinct sections, such that each section
addresses a separate concern.
20
SoC:SeperationOfConcerns,forexample
· JDBC
· MVC Pattern
· ReactiveX
21
Testing
// algebraic test:
// it tests the **rule** of the startsWith method.
// a and b is stateless, and startsWith has no sideEffect.
property("startsWith") = forAll { (a: String, b: String) =>
(a+b).startsWith(a)
}
22
AsynchronousProgramming
val task = Task {
// IO tasks ...
}
task.unsafePerformAsync(v =>
v.fold(e => e.printStackTrace(), a => println(a))
)
23
Caution!forFP
Only Consider the algorithm scale, not
performance.
24
Caution!forFP
val list = 1 to 10
// good
list
.map(a => a * a)
.foldLeft(0)((sum, a) => sum + a)
// bad
list
.foldLeft(0)((sum, a) => sum + a * a)
25
TheRulesfortheFunctionalProgramming
1. Elliminate the Side Effects
2. Don't use var keyword
3. Don't use new keyword
4. Use Unit type extremely carefully
5. Use case class
6. Define equals
26
FAQ
Q.Shouldilearnhaskell?
A. 필수는 아니다. 단, 더 나아가기 위해 Haskell이 도움
이 될 수 있다. 대부분의 Functional Programming 문
서는 Haskell을 위주로 설명돼있다.
27
FAQ
Q.PiS
A. 분량도 많고, 무엇보다 함수형 프로그래밍에 초점이
맞춰진 책이 아니어서 추천하지 않는다.
28
ChapterstoProceed
inFunctionalProgramminginScalaTextbook
1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13
29
Practices
30
PrintingStream
Write a program that prints the ints from 1 to 100.
1
2
…
100
31
FizzBuzz
Write a program that prints the ints from 1 to 100.
But:
- for multiples of three, print Fizz
- for multiples of five, print Buzz
- for multiples of both three and five, print
FizzBuzz
32
FizzBuzz
1
2
Fizz
4
Buzz
…
14
FizzBuzz
16
…
33
FizzBuzzinaRow
Write a fizzbuzz program that combines the
result with comma.
1, 2, Fizz, 4, Buzz, …, 98, Fizz, Buzz
34
OddNumber&to-200FizzBuzz
Write a fizzbuzz-in-a-row program with the odd
number stream from 1 to 199 .
1, Fizz, Buzz, …, 193, FizzBuzz, 197, 199
35
FurtherReadings
36
Grammars
· 스칼라 학교!
· 스칼라 공식 도큐먼트 입문
· Effective Scala by Twitter
· Effective Scala by Heejong Lee
· Hacker Rank for Tutorials
· Exercism
37
WhatisFunctionalProgramming?
· 함수형 프로그래밍이란 무엇인가?
· 어떤 프로그래밍 언어들이 함수형인가?
38
Textbooks&References
· ! 스칼라로 배우는 함수형 프로그래밍
· Functional Programming Principles in Scala on
Coursera
· Big Data Analysis with Scala and Spark on
Coursera
· Scala Excercises
39
PopularScalaLibraries
· ! Scalaz: Scala library for functional
programming
· Cats: Lightweight, modular, and extensible
library for functional programming
· Monix: Asynchronous Programming for Scala
· Circe: A JSON library for Scala powered by Cats
40
Haskell
· Eta Programming Language, Haskell on the
JVM
· (가장 쉬운) 하스켈 책 : 느긋하지만 우아하고 세련된
함수형 언어
41
Resources
· Scastie, an interactive playground for Scala
42

Functional Programming in Scala in a Nutshell: Review of Functional Programming in Scala Ch. 1