SlideShare a Scribd company logo
1 of 24
Download to read offline
Functional
Programming for All
Zachary McCoy
みんなの関数型プログラミング
About Me
• Scala
• Iowa, USA
• twitter - @ZachAMcCoy
• email - zach.mccoy@banno.com
What is Functional
Programming?
• Programming… with functions
• Functions as the main abstraction
• Functions as first class values
「関数を用いたプログラミング」
「関数を主な抽象化の道具とする」「第一級値としての関数」
What is Functional
Programming?
• Controlled side effects
• Restricts how we write programs, but not what we
can express
「制御された副作用」
「表現の幅は狭めずに、プログラムの書き方を制約する」
Functional Programming
• Pure functional core with a layer of side effects on
the outside
• Side effect - an action in addition to return
values
• FP - Evaluating expressions
• Imperative - programs are composed of statements
中核は純粋関数でその外側の層で副作用が実行される
FP は式を評価するのに対し、命令型は命令文から成る
What is a function?
• An expression involving one or more variables
• Domain and Co-Domain
• Unique mapping from D -> CD
• Immutability, produces something new
関数とは1つもしくは複数の値に関する式
ドメインとコドメインの一意対応、イミュータブル
Pure Functions
• No observable side-effects
• Anything that isn’t returning a result
• Mutation
• I/O
• Depends only on arguments or subset of
純粋関数は副作用を持たず、結果は引数にのみ依存する
Pure Functions
• Examples
• Hashing
• Arithmetic
純粋関数例:ハッシュ化、算術演算
Why does purity matter?
• Side effects cause order of evaluation to matter
• Only have to use local reasoning
• Composition and reusability
副作用は実行/評価順の考慮が必要になる、局所化、
合成と再利用性
Why does purity matter?
• Separate the computation over the input from how
to obtain it
• Guarantees Referential Transparency
演算と入力を与える方法を分離、参照透過性を保証
Referential Transparency
• An expression can be replaced by its value,
provided the expression is pure
• A function can only be RT if the inputs are also RT
• Referential Transparency enables equational
reasoning
参照透過性 (RT): 純粋な式がその値と置き換え可能なこと
関数が参照透過であるためには、入力も透過である必要がある
Substitution Model
def greaterThan5(i: Int): Option[Int] = 

if(i > 5) Some(i) else None



def createMessage(): String =

greaterThan5(3).map(x => "Was greater than 5") getOrElse "Was less than or equal to 5"

def createMessage2(): String =

(if(3 > 5)
Some(3)
else
None).map(x => "Was greater than 5") getOrElse "Was less than or equal to 5"

def createMessage3(): String =

None.map(x => "Was greater than 5") getOrElse "Was less than or equal to 5"

置き換えモデル
Formalize Referential
Transparency
• An expression, E, is said to be referentially
transparent if E can be replaced with its value
without changing the behavior of a program
• Same effect and output in the end
参照透過性の形式化:式をその値と置き換えることができる
プログラムの振る舞いは作用を含め変わってはいけない
Referential Transparency
• Mathematics!
• (2 * 2 = 4)
• Returning errors as values, rather than side
effecting
参照透過性は数学!
エラーは、副作用ではなく、値で返す
How does this tie together?
• Pure functions enable Referential Transparency
• RT enables the Substitution model and Equational
Reasoning
• Pure functions are a huge gain!
純粋関数 参照透過性 置き換えモデル&等式推論
純粋関数 ウマー
Scala and FP
• Scala doesn't enforce Referential Transparency
• We have to work for it
• Limit your set of tools: no vars, pulling from out of
scope, exceptions
Scala は参照透過性を強制しないため、自前での対応が必要
Scala and FP
• Given an impure function of type A => C we can
split it into two functions
• Pure function of A => B, where B is the
description of the result
• Impure function of type B => C which is the
interpreter of the description
純粋でない関数 A C は、純粋関数 A B と
そのインタプリタ B C に分離することが可能
Calculate the oldest
最年長者の計算
case class Person(name: String, age: Int)
val p1 = Person("John", 30)
val p2 = Person("Jack", 100)
Calculate the oldest
これはテストするのが難しい
全部副作用で出力されているので参照透過ではない
def calculateOldest(): Unit = {
if(p1.age > p2.age)
println(s"${p1.name} is oldest")
else if(p2.age > p1.age)
println(s"${p2.name} is oldest")
else
println("They are the same age")
}
Separation of concerns
関心事の分離
def calculateOldest(p1:Person, p2:Person):Unit
= {
if(p1.age > p2.age)
println(s"${p1.name} is oldest")
else if(p2.age > p1.age)
println(s"${p2.name} is oldest")
else
println(s"They are the same age")
}
Return values
戻り値を使うことでテストしやすくなった
def calculateOldest(p1: Person, p2: Person):
Option[Person] =
if(p1.age > p2.age)
Some(p1)
else if(p2.age > p1.age)
Some(p2)
else
None
We can still split more
さらに細かく分ける
def result(maybePerson:Option[Person]): Unit =
maybePerson match {
case Some(Person(name, age)) =>
println(s"${p.name} is oldest")
case None =>
println("They are the same age")
}
A pure function core
これでコアが純粋関数になった
def calculateOldest(p1: Person, p2: Person):
Option[Person]
def result(maybePerson: Option[Person]):
String =
maybePerson.map {
case Person(name, age) =>
s"${name} is the oldest"
} getOrElse "They are the same age"
def combine(p1: Person, p2: Person): Unit =
println(result(calculateOldest(p1,p2)))
We’re Hiring!
zach.mccoy@banno.com
一緒に働きませんか?

More Related Content

What's hot

Abstraction in java
Abstraction in javaAbstraction in java
Abstraction in java
sawarkar17
 
Functional Programming in Ruby
Functional Programming in RubyFunctional Programming in Ruby
Functional Programming in Ruby
Alex Teut
 
9781111530532 ppt ch02
9781111530532 ppt ch029781111530532 ppt ch02
9781111530532 ppt ch02
Terry Yoast
 

What's hot (18)

Lecture 4: Functions
Lecture 4: FunctionsLecture 4: Functions
Lecture 4: Functions
 
Abstraction in java
Abstraction in javaAbstraction in java
Abstraction in java
 
JavaScript Introductin to Functions
JavaScript Introductin to FunctionsJavaScript Introductin to Functions
JavaScript Introductin to Functions
 
Operators in java
Operators in javaOperators in java
Operators in java
 
PL/SQL Example for IF .. ELSIF
PL/SQL Example for IF .. ELSIFPL/SQL Example for IF .. ELSIF
PL/SQL Example for IF .. ELSIF
 
Functional Programming in Ruby
Functional Programming in RubyFunctional Programming in Ruby
Functional Programming in Ruby
 
Why functional programming in C# & F#
Why functional programming in C# & F#Why functional programming in C# & F#
Why functional programming in C# & F#
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
Pure functions and usage in Angular
Pure functions and usage in AngularPure functions and usage in Angular
Pure functions and usage in Angular
 
Java 8 Functional Programming - I
Java 8 Functional Programming - IJava 8 Functional Programming - I
Java 8 Functional Programming - I
 
AOP
AOPAOP
AOP
 
Programming in python w6
Programming in python w6Programming in python w6
Programming in python w6
 
Python Built-in Functions and Use cases
Python Built-in Functions and Use casesPython Built-in Functions and Use cases
Python Built-in Functions and Use cases
 
Java script function
Java script functionJava script function
Java script function
 
9781111530532 ppt ch02
9781111530532 ppt ch029781111530532 ppt ch02
9781111530532 ppt ch02
 
Inline functions in c++
Inline functions in c++Inline functions in c++
Inline functions in c++
 
Inline functions & macros
Inline functions & macrosInline functions & macros
Inline functions & macros
 
Functional Programming in Python
Functional Programming in PythonFunctional Programming in Python
Functional Programming in Python
 

Viewers also liked

Scala Warrior and type-safe front-end development with Scala.js
Scala Warrior and type-safe front-end development with Scala.jsScala Warrior and type-safe front-end development with Scala.js
Scala Warrior and type-safe front-end development with Scala.js
takezoe
 
Tracing Microservices with Zipkin
Tracing Microservices with ZipkinTracing Microservices with Zipkin
Tracing Microservices with Zipkin
takezoe
 

Viewers also liked (20)

Contributing to Scala OSS from East Asia #ScalaMatsuri
 Contributing to Scala OSS from East Asia #ScalaMatsuri Contributing to Scala OSS from East Asia #ScalaMatsuri
Contributing to Scala OSS from East Asia #ScalaMatsuri
 
バッチを Akka Streams で再実装したら100倍速くなった話 #ScalaMatsuri
バッチを Akka Streams で再実装したら100倍速くなった話 #ScalaMatsuriバッチを Akka Streams で再実装したら100倍速くなった話 #ScalaMatsuri
バッチを Akka Streams で再実装したら100倍速くなった話 #ScalaMatsuri
 
Zen of Akka
Zen of AkkaZen of Akka
Zen of Akka
 
ScalaMatsuri 2016
ScalaMatsuri 2016ScalaMatsuri 2016
ScalaMatsuri 2016
 
Scala Refactoring for Fun and Profit (Japanese subtitles)
Scala Refactoring for Fun and Profit (Japanese subtitles)Scala Refactoring for Fun and Profit (Japanese subtitles)
Scala Refactoring for Fun and Profit (Japanese subtitles)
 
あなたのScalaを爆速にする7つの方法(日本語版)
あなたのScalaを爆速にする7つの方法(日本語版)あなたのScalaを爆速にする7つの方法(日本語版)
あなたのScalaを爆速にする7つの方法(日本語版)
 
Scala Matsuri 2016: Japanese Text Mining with Scala and Spark
Scala Matsuri 2016: Japanese Text Mining with Scala and SparkScala Matsuri 2016: Japanese Text Mining with Scala and Spark
Scala Matsuri 2016: Japanese Text Mining with Scala and Spark
 
Reactive database access with Slick3
Reactive database access with Slick3Reactive database access with Slick3
Reactive database access with Slick3
 
How Scala code is expressed in the JVM
How Scala code is expressed in the JVMHow Scala code is expressed in the JVM
How Scala code is expressed in the JVM
 
Why Reactive Matters #ScalaMatsuri
Why Reactive Matters #ScalaMatsuriWhy Reactive Matters #ScalaMatsuri
Why Reactive Matters #ScalaMatsuri
 
Functional and Algebraic Domain Modeling
Functional and Algebraic Domain ModelingFunctional and Algebraic Domain Modeling
Functional and Algebraic Domain Modeling
 
Thinking in Cats
Thinking in CatsThinking in Cats
Thinking in Cats
 
Scala Warrior and type-safe front-end development with Scala.js
Scala Warrior and type-safe front-end development with Scala.jsScala Warrior and type-safe front-end development with Scala.js
Scala Warrior and type-safe front-end development with Scala.js
 
Arquitectura barroca
Arquitectura barrocaArquitectura barroca
Arquitectura barroca
 
究極のPHP本完成
究極のPHP本完成究極のPHP本完成
究極のPHP本完成
 
Sbtのマルチプロジェクトはいいぞ
SbtのマルチプロジェクトはいいぞSbtのマルチプロジェクトはいいぞ
Sbtのマルチプロジェクトはいいぞ
 
KamonとDatadogによるリアクティブアプリケーションの監視の事例
KamonとDatadogによるリアクティブアプリケーションの監視の事例KamonとDatadogによるリアクティブアプリケーションの監視の事例
KamonとDatadogによるリアクティブアプリケーションの監視の事例
 
Rubyからscalaに変えるべき15の理由
Rubyからscalaに変えるべき15の理由Rubyからscalaに変えるべき15の理由
Rubyからscalaに変えるべき15の理由
 
Akka Cluster and Auto-scaling
Akka Cluster and Auto-scalingAkka Cluster and Auto-scaling
Akka Cluster and Auto-scaling
 
Tracing Microservices with Zipkin
Tracing Microservices with ZipkinTracing Microservices with Zipkin
Tracing Microservices with Zipkin
 

Similar to Functional Programming For All - Scala Matsuri 2016

379008-rc217-functionalprogramming
379008-rc217-functionalprogramming379008-rc217-functionalprogramming
379008-rc217-functionalprogramming
Luis Atencio
 
Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptx
miki304759
 

Similar to Functional Programming For All - Scala Matsuri 2016 (20)

Functional programming
Functional programmingFunctional programming
Functional programming
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
Python Functions
Python FunctionsPython Functions
Python Functions
 
Scala Programming Introduction
Scala Programming IntroductionScala Programming Introduction
Scala Programming Introduction
 
Definitions of Functional Programming
Definitions of Functional ProgrammingDefinitions of Functional Programming
Definitions of Functional Programming
 
Oops concept in Java
Oops concept in JavaOops concept in Java
Oops concept in Java
 
Functional JavaScript Fundamentals
Functional JavaScript FundamentalsFunctional JavaScript Fundamentals
Functional JavaScript Fundamentals
 
Functional Swift
Functional SwiftFunctional Swift
Functional Swift
 
Functional Programing Principles
Functional Programing PrinciplesFunctional Programing Principles
Functional Programing Principles
 
Functional Paradigm.pptx
Functional Paradigm.pptxFunctional Paradigm.pptx
Functional Paradigm.pptx
 
Python functional programming
Python functional programmingPython functional programming
Python functional programming
 
Functional Programming in C#
Functional Programming in C#Functional Programming in C#
Functional Programming in C#
 
Functional programing jargon
Functional programing jargonFunctional programing jargon
Functional programing jargon
 
379008-rc217-functionalprogramming
379008-rc217-functionalprogramming379008-rc217-functionalprogramming
379008-rc217-functionalprogramming
 
Functional programming for the Advanced Beginner
Functional programming for the Advanced BeginnerFunctional programming for the Advanced Beginner
Functional programming for the Advanced Beginner
 
Functional Programming in JavaScript & ESNext
Functional Programming in JavaScript & ESNextFunctional Programming in JavaScript & ESNext
Functional Programming in JavaScript & ESNext
 
Functional programmning
Functional programmningFunctional programmning
Functional programmning
 
Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptx
 
Insight into java 1.8, OOP VS FP
Insight into java 1.8, OOP VS FPInsight into java 1.8, OOP VS FP
Insight into java 1.8, OOP VS FP
 
Functional Programmer's Starter Kit
Functional Programmer's Starter KitFunctional Programmer's Starter Kit
Functional Programmer's Starter Kit
 

Recently uploaded

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 

Recently uploaded (20)

Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 

Functional Programming For All - Scala Matsuri 2016

  • 1. Functional Programming for All Zachary McCoy みんなの関数型プログラミング
  • 2. About Me • Scala • Iowa, USA • twitter - @ZachAMcCoy • email - zach.mccoy@banno.com
  • 3. What is Functional Programming? • Programming… with functions • Functions as the main abstraction • Functions as first class values 「関数を用いたプログラミング」 「関数を主な抽象化の道具とする」「第一級値としての関数」
  • 4. What is Functional Programming? • Controlled side effects • Restricts how we write programs, but not what we can express 「制御された副作用」 「表現の幅は狭めずに、プログラムの書き方を制約する」
  • 5. Functional Programming • Pure functional core with a layer of side effects on the outside • Side effect - an action in addition to return values • FP - Evaluating expressions • Imperative - programs are composed of statements 中核は純粋関数でその外側の層で副作用が実行される FP は式を評価するのに対し、命令型は命令文から成る
  • 6. What is a function? • An expression involving one or more variables • Domain and Co-Domain • Unique mapping from D -> CD • Immutability, produces something new 関数とは1つもしくは複数の値に関する式 ドメインとコドメインの一意対応、イミュータブル
  • 7. Pure Functions • No observable side-effects • Anything that isn’t returning a result • Mutation • I/O • Depends only on arguments or subset of 純粋関数は副作用を持たず、結果は引数にのみ依存する
  • 8. Pure Functions • Examples • Hashing • Arithmetic 純粋関数例:ハッシュ化、算術演算
  • 9. Why does purity matter? • Side effects cause order of evaluation to matter • Only have to use local reasoning • Composition and reusability 副作用は実行/評価順の考慮が必要になる、局所化、 合成と再利用性
  • 10. Why does purity matter? • Separate the computation over the input from how to obtain it • Guarantees Referential Transparency 演算と入力を与える方法を分離、参照透過性を保証
  • 11. Referential Transparency • An expression can be replaced by its value, provided the expression is pure • A function can only be RT if the inputs are also RT • Referential Transparency enables equational reasoning 参照透過性 (RT): 純粋な式がその値と置き換え可能なこと 関数が参照透過であるためには、入力も透過である必要がある
  • 12. Substitution Model def greaterThan5(i: Int): Option[Int] = if(i > 5) Some(i) else None def createMessage(): String = greaterThan5(3).map(x => "Was greater than 5") getOrElse "Was less than or equal to 5" def createMessage2(): String = (if(3 > 5) Some(3) else None).map(x => "Was greater than 5") getOrElse "Was less than or equal to 5" def createMessage3(): String = None.map(x => "Was greater than 5") getOrElse "Was less than or equal to 5" 置き換えモデル
  • 13. Formalize Referential Transparency • An expression, E, is said to be referentially transparent if E can be replaced with its value without changing the behavior of a program • Same effect and output in the end 参照透過性の形式化:式をその値と置き換えることができる プログラムの振る舞いは作用を含め変わってはいけない
  • 14. Referential Transparency • Mathematics! • (2 * 2 = 4) • Returning errors as values, rather than side effecting 参照透過性は数学! エラーは、副作用ではなく、値で返す
  • 15. How does this tie together? • Pure functions enable Referential Transparency • RT enables the Substitution model and Equational Reasoning • Pure functions are a huge gain! 純粋関数 参照透過性 置き換えモデル&等式推論 純粋関数 ウマー
  • 16. Scala and FP • Scala doesn't enforce Referential Transparency • We have to work for it • Limit your set of tools: no vars, pulling from out of scope, exceptions Scala は参照透過性を強制しないため、自前での対応が必要
  • 17. Scala and FP • Given an impure function of type A => C we can split it into two functions • Pure function of A => B, where B is the description of the result • Impure function of type B => C which is the interpreter of the description 純粋でない関数 A C は、純粋関数 A B と そのインタプリタ B C に分離することが可能
  • 18. Calculate the oldest 最年長者の計算 case class Person(name: String, age: Int) val p1 = Person("John", 30) val p2 = Person("Jack", 100)
  • 19. Calculate the oldest これはテストするのが難しい 全部副作用で出力されているので参照透過ではない def calculateOldest(): Unit = { if(p1.age > p2.age) println(s"${p1.name} is oldest") else if(p2.age > p1.age) println(s"${p2.name} is oldest") else println("They are the same age") }
  • 20. Separation of concerns 関心事の分離 def calculateOldest(p1:Person, p2:Person):Unit = { if(p1.age > p2.age) println(s"${p1.name} is oldest") else if(p2.age > p1.age) println(s"${p2.name} is oldest") else println(s"They are the same age") }
  • 21. Return values 戻り値を使うことでテストしやすくなった def calculateOldest(p1: Person, p2: Person): Option[Person] = if(p1.age > p2.age) Some(p1) else if(p2.age > p1.age) Some(p2) else None
  • 22. We can still split more さらに細かく分ける def result(maybePerson:Option[Person]): Unit = maybePerson match { case Some(Person(name, age)) => println(s"${p.name} is oldest") case None => println("They are the same age") }
  • 23. A pure function core これでコアが純粋関数になった def calculateOldest(p1: Person, p2: Person): Option[Person] def result(maybePerson: Option[Person]): String = maybePerson.map { case Person(name, age) => s"${name} is the oldest" } getOrElse "They are the same age" def combine(p1: Person, p2: Person): Unit = println(result(calculateOldest(p1,p2)))