Functional Programming For All - Scala Matsuri 2016

Z
Zachary AbbottSoftware Engineer at Jack Henry & Associates
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
一緒に働きませんか?
1 of 24

Recommended

Functional Programming in Java by
Functional Programming in JavaFunctional Programming in Java
Functional Programming in JavaNarendran Solai Sridharan
495 views56 slides
Why should a Java programmer shifts towards Functional Programming Paradigm by
Why should a Java programmer shifts towards Functional Programming ParadigmWhy should a Java programmer shifts towards Functional Programming Paradigm
Why should a Java programmer shifts towards Functional Programming ParadigmTech Triveni
246 views27 slides
Designing function families and bundles with java's behaviors parameterisatio... by
Designing function families and bundles with java's behaviors parameterisatio...Designing function families and bundles with java's behaviors parameterisatio...
Designing function families and bundles with java's behaviors parameterisatio...Alain Lompo
52 views37 slides
XII Computer Science- Chapter 1-Function by
XII  Computer Science- Chapter 1-FunctionXII  Computer Science- Chapter 1-Function
XII Computer Science- Chapter 1-FunctionPrem Joel
567 views23 slides
Operators in java By cheena by
Operators in java By cheenaOperators in java By cheena
Operators in java By cheenaChëëñå Båbü
16 views29 slides
Introduction to Functional programming by
Introduction to Functional programmingIntroduction to Functional programming
Introduction to Functional programmingNy Fanilo Andrianjafy, B.Eng.
451 views38 slides

More Related Content

What's hot

Lecture 4: Functions by
Lecture 4: FunctionsLecture 4: Functions
Lecture 4: FunctionsVivek Bhargav
161 views23 slides
Abstraction in java by
Abstraction in javaAbstraction in java
Abstraction in javasawarkar17
5.7K views5 slides
JavaScript Introductin to Functions by
JavaScript Introductin to FunctionsJavaScript Introductin to Functions
JavaScript Introductin to FunctionsCharles Russell
557 views11 slides
Operators in java by
Operators in javaOperators in java
Operators in javaAbhishekMondal42
236 views24 slides
PL/SQL Example for IF .. ELSIF by
PL/SQL Example for IF .. ELSIFPL/SQL Example for IF .. ELSIF
PL/SQL Example for IF .. ELSIFKai Liu
1.3K views6 slides
Functional Programming in Ruby by
Functional Programming in RubyFunctional Programming in Ruby
Functional Programming in RubyAlex Teut
925 views30 slides

What's hot(18)

Abstraction in java by sawarkar17
Abstraction in javaAbstraction in java
Abstraction in java
sawarkar175.7K views
JavaScript Introductin to Functions by Charles Russell
JavaScript Introductin to FunctionsJavaScript Introductin to Functions
JavaScript Introductin to Functions
Charles Russell557 views
PL/SQL Example for IF .. ELSIF by Kai Liu
PL/SQL Example for IF .. ELSIFPL/SQL Example for IF .. ELSIF
PL/SQL Example for IF .. ELSIF
Kai Liu1.3K views
Functional Programming in Ruby by Alex Teut
Functional Programming in RubyFunctional Programming in Ruby
Functional Programming in Ruby
Alex Teut925 views
Why functional programming in C# & F# by Riccardo Terrell
Why functional programming in C# & F#Why functional programming in C# & F#
Why functional programming in C# & F#
Riccardo Terrell1.5K views
Functional programming by ijcd
Functional programmingFunctional programming
Functional programming
ijcd1.4K views
Pure functions and usage in Angular by MA Jiangfan
Pure functions and usage in AngularPure functions and usage in Angular
Pure functions and usage in Angular
MA Jiangfan400 views
Java 8 Functional Programming - I by Ugur Yeter
Java 8 Functional Programming - IJava 8 Functional Programming - I
Java 8 Functional Programming - I
Ugur Yeter187 views
Programming in python w6 by Priya Nayak
Programming in python w6Programming in python w6
Programming in python w6
Priya Nayak15 views
Python Built-in Functions and Use cases by Srajan Mor
Python Built-in Functions and Use casesPython Built-in Functions and Use cases
Python Built-in Functions and Use cases
Srajan Mor359 views
9781111530532 ppt ch02 by Terry Yoast
9781111530532 ppt ch029781111530532 ppt ch02
9781111530532 ppt ch02
Terry Yoast413 views
Inline functions & macros by Anand Kumar
Inline functions & macrosInline functions & macros
Inline functions & macros
Anand Kumar1.7K views
Functional Programming in Python by Haim Michael
Functional Programming in PythonFunctional Programming in Python
Functional Programming in Python
Haim Michael753 views

Viewers also liked

Contributing to Scala OSS from East Asia #ScalaMatsuri by
 Contributing to Scala OSS from East Asia #ScalaMatsuri Contributing to Scala OSS from East Asia #ScalaMatsuri
Contributing to Scala OSS from East Asia #ScalaMatsuriKazuhiro Sera
10.9K views37 slides
バッチを Akka Streams で再実装したら100倍速くなった話 #ScalaMatsuri by
バッチを Akka Streams で再実装したら100倍速くなった話 #ScalaMatsuriバッチを Akka Streams で再実装したら100倍速くなった話 #ScalaMatsuri
バッチを Akka Streams で再実装したら100倍速くなった話 #ScalaMatsuriKazuki Negoro
24K views59 slides
Zen of Akka by
Zen of AkkaZen of Akka
Zen of AkkaKonrad Malawski
29.4K views136 slides
ScalaMatsuri 2016 by
ScalaMatsuri 2016ScalaMatsuri 2016
ScalaMatsuri 2016Yoshitaka Fujii
7.1K views151 slides
Scala Refactoring for Fun and Profit (Japanese subtitles) by
Scala Refactoring for Fun and Profit (Japanese subtitles)Scala Refactoring for Fun and Profit (Japanese subtitles)
Scala Refactoring for Fun and Profit (Japanese subtitles)Tomer Gabel
6.6K views16 slides
あなたのScalaを爆速にする7つの方法(日本語版) by
あなたのScalaを爆速にする7つの方法(日本語版)あなたのScalaを爆速にする7つの方法(日本語版)
あなたのScalaを爆速にする7つの方法(日本語版)x1 ichi
14.2K views74 slides

Viewers also liked(20)

Contributing to Scala OSS from East Asia #ScalaMatsuri by Kazuhiro Sera
 Contributing to Scala OSS from East Asia #ScalaMatsuri Contributing to Scala OSS from East Asia #ScalaMatsuri
Contributing to Scala OSS from East Asia #ScalaMatsuri
Kazuhiro Sera10.9K views
バッチを Akka Streams で再実装したら100倍速くなった話 #ScalaMatsuri by Kazuki Negoro
バッチを Akka Streams で再実装したら100倍速くなった話 #ScalaMatsuriバッチを Akka Streams で再実装したら100倍速くなった話 #ScalaMatsuri
バッチを Akka Streams で再実装したら100倍速くなった話 #ScalaMatsuri
Kazuki Negoro24K views
Scala Refactoring for Fun and Profit (Japanese subtitles) by Tomer Gabel
Scala Refactoring for Fun and Profit (Japanese subtitles)Scala Refactoring for Fun and Profit (Japanese subtitles)
Scala Refactoring for Fun and Profit (Japanese subtitles)
Tomer Gabel6.6K views
あなたのScalaを爆速にする7つの方法(日本語版) by x1 ichi
あなたのScalaを爆速にする7つの方法(日本語版)あなたのScalaを爆速にする7つの方法(日本語版)
あなたのScalaを爆速にする7つの方法(日本語版)
x1 ichi14.2K views
Scala Matsuri 2016: Japanese Text Mining with Scala and Spark by Eduardo Gonzalez
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
Eduardo Gonzalez3.9K views
Reactive database access with Slick3 by takezoe
Reactive database access with Slick3Reactive database access with Slick3
Reactive database access with Slick3
takezoe5.2K views
How Scala code is expressed in the JVM by Koichi Sakata
How Scala code is expressed in the JVMHow Scala code is expressed in the JVM
How Scala code is expressed in the JVM
Koichi Sakata8.3K views
Why Reactive Matters #ScalaMatsuri by Yuta Okamoto
Why Reactive Matters #ScalaMatsuriWhy Reactive Matters #ScalaMatsuri
Why Reactive Matters #ScalaMatsuri
Yuta Okamoto15.5K views
Functional and Algebraic Domain Modeling by Debasish Ghosh
Functional and Algebraic Domain ModelingFunctional and Algebraic Domain Modeling
Functional and Algebraic Domain Modeling
Debasish Ghosh5.7K views
Scala Warrior and type-safe front-end development with Scala.js by takezoe
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
takezoe9.3K views
Sbtのマルチプロジェクトはいいぞ by Yoshitaka Fujii
SbtのマルチプロジェクトはいいぞSbtのマルチプロジェクトはいいぞ
Sbtのマルチプロジェクトはいいぞ
Yoshitaka Fujii1.4K views
KamonとDatadogによるリアクティブアプリケーションの監視の事例 by Ikuo Matsumura
KamonとDatadogによるリアクティブアプリケーションの監視の事例KamonとDatadogによるリアクティブアプリケーションの監視の事例
KamonとDatadogによるリアクティブアプリケーションの監視の事例
Ikuo Matsumura2.2K views
Rubyからscalaに変えるべき15の理由 by Yukishige Nakajo
Rubyからscalaに変えるべき15の理由Rubyからscalaに変えるべき15の理由
Rubyからscalaに変えるべき15の理由
Yukishige Nakajo19.8K views
Akka Cluster and Auto-scaling by Ikuo Matsumura
Akka Cluster and Auto-scalingAkka Cluster and Auto-scaling
Akka Cluster and Auto-scaling
Ikuo Matsumura2.9K views
Tracing Microservices with Zipkin by takezoe
Tracing Microservices with ZipkinTracing Microservices with Zipkin
Tracing Microservices with Zipkin
takezoe13.8K views

Similar to Functional Programming For All - Scala Matsuri 2016

Functional programming by
Functional programmingFunctional programming
Functional programmingPiumiPerera7
116 views55 slides
Functional programming by
Functional programmingFunctional programming
Functional programmingKibru Demeke
73 views20 slides
Python Functions by
Python FunctionsPython Functions
Python FunctionsBrainware University
4 views14 slides
Scala Programming Introduction by
Scala Programming IntroductionScala Programming Introduction
Scala Programming IntroductionairisData
1.1K views11 slides
Definitions of Functional Programming by
Definitions of Functional ProgrammingDefinitions of Functional Programming
Definitions of Functional ProgrammingPhilip Schwarz
1.1K views7 slides
Oops concept in Java by
Oops concept in JavaOops concept in Java
Oops concept in JavaDucat India
53 views5 slides

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

Functional programming by PiumiPerera7
Functional programmingFunctional programming
Functional programming
PiumiPerera7116 views
Scala Programming Introduction by airisData
Scala Programming IntroductionScala Programming Introduction
Scala Programming Introduction
airisData1.1K views
Definitions of Functional Programming by Philip Schwarz
Definitions of Functional ProgrammingDefinitions of Functional Programming
Definitions of Functional Programming
Philip Schwarz1.1K views
Oops concept in Java by Ducat India
Oops concept in JavaOops concept in Java
Oops concept in Java
Ducat India53 views
Functional Swift by Geison Goes
Functional SwiftFunctional Swift
Functional Swift
Geison Goes232 views
Functional Programing Principles by Jiaming Zhang
Functional Programing PrinciplesFunctional Programing Principles
Functional Programing Principles
Jiaming Zhang708 views
Python functional programming by Geison Goes
Python functional programmingPython functional programming
Python functional programming
Geison Goes3.2K views
Functional Programming in C# by Tadeusz Balcer
Functional Programming in C#Functional Programming in C#
Functional Programming in C#
Tadeusz Balcer240 views
Functional programing jargon by Remo Jansen
Functional programing jargonFunctional programing jargon
Functional programing jargon
Remo Jansen682 views
379008-rc217-functionalprogramming by Luis Atencio
379008-rc217-functionalprogramming379008-rc217-functionalprogramming
379008-rc217-functionalprogramming
Luis Atencio217 views
Functional programming for the Advanced Beginner by Luis Atencio
Functional programming for the Advanced BeginnerFunctional programming for the Advanced Beginner
Functional programming for the Advanced Beginner
Luis Atencio798 views
Functional Programming in JavaScript & ESNext by Unfold UI
Functional Programming in JavaScript & ESNextFunctional Programming in JavaScript & ESNext
Functional Programming in JavaScript & ESNext
Unfold UI734 views
Chapter One Function.pptx by miki304759
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptx
miki30475913 views
Functional Programmer's Starter Kit by Garreth Dottin
Functional Programmer's Starter KitFunctional Programmer's Starter Kit
Functional Programmer's Starter Kit
Garreth Dottin170 views

Recently uploaded

ShortStory_qlora.pptx by
ShortStory_qlora.pptxShortStory_qlora.pptx
ShortStory_qlora.pptxpranathikrishna22
5 views10 slides
SAP FOR TYRE INDUSTRY.pdf by
SAP FOR TYRE INDUSTRY.pdfSAP FOR TYRE INDUSTRY.pdf
SAP FOR TYRE INDUSTRY.pdfVirendra Rai, PMP
24 views3 slides
Ports-and-Adapters Architecture for Embedded HMI by
Ports-and-Adapters Architecture for Embedded HMIPorts-and-Adapters Architecture for Embedded HMI
Ports-and-Adapters Architecture for Embedded HMIBurkhard Stubert
21 views19 slides
Keep by
KeepKeep
KeepGeniusee
77 views10 slides
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P... by
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...NimaTorabi2
12 views17 slides
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ... by
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...Donato Onofri
860 views34 slides

Recently uploaded(20)

Ports-and-Adapters Architecture for Embedded HMI by Burkhard Stubert
Ports-and-Adapters Architecture for Embedded HMIPorts-and-Adapters Architecture for Embedded HMI
Ports-and-Adapters Architecture for Embedded HMI
Burkhard Stubert21 views
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P... by NimaTorabi2
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...
NimaTorabi212 views
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ... by Donato Onofri
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...
Donato Onofri860 views
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium... by Lisi Hocke
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...
Lisi Hocke35 views
Headless JS UG Presentation.pptx by Jack Spektor
Headless JS UG Presentation.pptxHeadless JS UG Presentation.pptx
Headless JS UG Presentation.pptx
Jack Spektor8 views
20231129 - Platform @ localhost 2023 - Application-driven infrastructure with... by sparkfabrik
20231129 - Platform @ localhost 2023 - Application-driven infrastructure with...20231129 - Platform @ localhost 2023 - Application-driven infrastructure with...
20231129 - Platform @ localhost 2023 - Application-driven infrastructure with...
sparkfabrik7 views
Software evolution understanding: Automatic extraction of software identifier... by Ra'Fat Al-Msie'deen
Software evolution understanding: Automatic extraction of software identifier...Software evolution understanding: Automatic extraction of software identifier...
Software evolution understanding: Automatic extraction of software identifier...
Navigating container technology for enhanced security by Niklas Saari by Metosin Oy
Navigating container technology for enhanced security by Niklas SaariNavigating container technology for enhanced security by Niklas Saari
Navigating container technology for enhanced security by Niklas Saari
Metosin Oy14 views
Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated... by TomHalpin9
Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated...Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated...
Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated...
TomHalpin96 views
AI and Ml presentation .pptx by FayazAli87
AI and Ml presentation .pptxAI and Ml presentation .pptx
AI and Ml presentation .pptx
FayazAli8712 views
DSD-INT 2023 European Digital Twin Ocean and Delft3D FM - Dols by Deltares
DSD-INT 2023 European Digital Twin Ocean and Delft3D FM - DolsDSD-INT 2023 European Digital Twin Ocean and Delft3D FM - Dols
DSD-INT 2023 European Digital Twin Ocean and Delft3D FM - Dols
Deltares9 views
Sprint 226 by ManageIQ
Sprint 226Sprint 226
Sprint 226
ManageIQ5 views
Dapr Unleashed: Accelerating Microservice Development by Miroslav Janeski
Dapr Unleashed: Accelerating Microservice DevelopmentDapr Unleashed: Accelerating Microservice Development
Dapr Unleashed: Accelerating Microservice Development
Miroslav Janeski10 views
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx by animuscrm
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx
animuscrm15 views

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)))