SlideShare a Scribd company logo
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

More Related Content

PDF
BeepBeep 3: A declarative event stream query engine (EDOC 2015)
PPSX
PDF
Anjalisoorej imca133 assignment
PPTX
Stack using Array
PPTX
Stack of Data structure
PPTX
Stack using Linked List
BeepBeep 3: A declarative event stream query engine (EDOC 2015)
Anjalisoorej imca133 assignment
Stack using Array
Stack of Data structure
Stack using Linked List

What's hot (20)

PDF
Recursion concepts by Divya
PDF
Stack concepts by Divya
PPTX
Application of Stack - Yadraj Meena
PPT
Looping in C
DOCX
DOCX
Applications of list
PPT
Stack linked list
PDF
ICP - Lecture 9
PDF
Java Class Design
PPT
Stacks and queue
PPT
Stack application
PPT
Conversion of Infix To Postfix Expressions
DOCX
PPT
StackArray stack3
PPTX
Lambda выражения и Java 8
PPTX
[DevDay2018] How does JavaScript actually work? - By: Vi Nguyen, Senior Softw...
PDF
Rcpp11 genentech
PDF
Applications of stack
PPTX
Stack and its Applications : Data Structures ADT
Recursion concepts by Divya
Stack concepts by Divya
Application of Stack - Yadraj Meena
Looping in C
Applications of list
Stack linked list
ICP - Lecture 9
Java Class Design
Stacks and queue
Stack application
Conversion of Infix To Postfix Expressions
StackArray stack3
Lambda выражения и Java 8
[DevDay2018] How does JavaScript actually work? - By: Vi Nguyen, Senior Softw...
Rcpp11 genentech
Applications of stack
Stack and its Applications : Data Structures ADT
Ad

Viewers also liked (20)

PDF
Why Scala?
PPTX
A Brief Intro to Scala
PDF
Learn 90% of Python in 90 Minutes
PDF
Introduction to Functional Programming with Scala
PDF
Review of Calculation Paradigm and its Components
PPT
Final1
PDF
High Wizardry in the Land of Scala
PDF
夏俊鸾:Spark——基于内存的下一代大数据分析框架
PPTX
Big data hadoop FAQ's
PDF
Java/Scala Lab 2016. Руслан Шевченко: Несколько трюков scala-разработки, приг...
PDF
Big Data eBook
PDF
Spark as a distributed Scala
PPTX
ELIXIR Webinar: Introducing TeSS
PDF
WEB MINING: PATTERN DISCOVERY ON THE WORLD WIDE WEB - 2011
PDF
Magic Clusters and Where to Find Them 2.0 - Eugene Pirogov
PPTX
나프다 웨비너 1604: Elixir와 함수형 프로그래밍을 이용한 웹 개발
PPTX
Control flow in_elixir
PDF
Spring IO for startups
PDF
Python: the Project, the Language and the Style
PDF
Flowex: Flow-Based Programming with Elixir GenStage - Anton Mishchuk
Why Scala?
A Brief Intro to Scala
Learn 90% of Python in 90 Minutes
Introduction to Functional Programming with Scala
Review of Calculation Paradigm and its Components
Final1
High Wizardry in the Land of Scala
夏俊鸾:Spark——基于内存的下一代大数据分析框架
Big data hadoop FAQ's
Java/Scala Lab 2016. Руслан Шевченко: Несколько трюков scala-разработки, приг...
Big Data eBook
Spark as a distributed Scala
ELIXIR Webinar: Introducing TeSS
WEB MINING: PATTERN DISCOVERY ON THE WORLD WIDE WEB - 2011
Magic Clusters and Where to Find Them 2.0 - Eugene Pirogov
나프다 웨비너 1604: Elixir와 함수형 프로그래밍을 이용한 웹 개발
Control flow in_elixir
Spring IO for startups
Python: the Project, the Language and the Style
Flowex: Flow-Based Programming with Elixir GenStage - Anton Mishchuk
Ad

Similar to Functional Programming in Scala in a Nutshell: Review of Functional Programming in Scala Ch. 1 (20)

PDF
Functional Programming in Scala in a Nutshell
ODP
Functional programming
PDF
Real World Haskell: Lecture 1
PDF
BUILDING APPS WITH ASYNCIO
PPTX
Functuon
PPTX
Functuon
PPT
LECTURE 5-Function in Matlab how to use mathlab
PDF
2Bytesprog2 course_2014_c8_units
PPTX
Столпы функционального программирования для адептов ООП, Николай Мозговой
PDF
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2
PDF
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...
PDF
JavaScript(Es5) Interview Questions & Answers
PDF
Using Flow-based programming to write tools and workflows for Scientific Comp...
PDF
エンタープライズ・クラウドと 並列・分散・非同期処理
PDF
CLISP Lab Manual - Dr.J.VijiPriya
ODP
Functional programming with Scala
ODP
PPTX
luckfuckfunctioneekefkfejewnfiwnfnenf.pptx
PPTX
Introduction to kotlin
Functional Programming in Scala in a Nutshell
Functional programming
Real World Haskell: Lecture 1
BUILDING APPS WITH ASYNCIO
Functuon
Functuon
LECTURE 5-Function in Matlab how to use mathlab
2Bytesprog2 course_2014_c8_units
Столпы функционального программирования для адептов ООП, Николай Мозговой
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...
JavaScript(Es5) Interview Questions & Answers
Using Flow-based programming to write tools and workflows for Scientific Comp...
エンタープライズ・クラウドと 並列・分散・非同期処理
CLISP Lab Manual - Dr.J.VijiPriya
Functional programming with Scala
luckfuckfunctioneekefkfejewnfiwnfnenf.pptx
Introduction to kotlin

Recently uploaded (20)

PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PPTX
Computer Software and OS of computer science of grade 11.pptx
PPTX
history of c programming in notes for students .pptx
PDF
Digital Systems & Binary Numbers (comprehensive )
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
System and Network Administration Chapter 2
PPTX
Reimagine Home Health with the Power of Agentic AI​
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Computer Software and OS of computer science of grade 11.pptx
history of c programming in notes for students .pptx
Digital Systems & Binary Numbers (comprehensive )
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Design an Analysis of Algorithms II-SECS-1021-03
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Which alternative to Crystal Reports is best for small or large businesses.pdf
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
VVF-Customer-Presentation2025-Ver1.9.pptx
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Odoo Companies in India – Driving Business Transformation.pdf
System and Network Administration Chapter 2
Reimagine Home Health with the Power of Agentic AI​
Softaken Excel to vCard Converter Software.pdf
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Wondershare Filmora 15 Crack With Activation Key [2025
2025 Textile ERP Trends: SAP, Odoo & Oracle
Lecture 3: Operating Systems Introduction to Computer Hardware Systems

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