SlideShare a Scribd company logo
www.dotnetconf.net
Introducing Functional Programming in
C#
Kevin Yang, Sam Xiao
• Angular Taiwan、Angular Girls Taiwan 、TypeScript Taiwan 社群管理
者
• Angular 線上讀書會主持人
• Angular/Web GDE (Google Developer Expert) 開發專家
• 微軟最有價值專家(Visual Studio and Development Technologies)。
• 部落格:https://blog.kevinyang.net/
• FB粉絲頁:https://www.facebook.com/CKNotepad/
About Kevin
• Laravel 台中社群小聚 2016 講師
• Community Open Camp 2016 講師
• PHPConf 2016 講師
• COSCUP 2017 講師
• Angular 台北社群小聚 2017 講師
• 微軟最有價值專家(Visual Studio and Development Technologies)
• 部落格:點燈坊
• FB 粉絲頁 : 點燈坊
About Sam
• Introduction
• Definition
• FP 文藝復興
• OOP vs. FP
• C# 對 FP 支援
• 如何學習與導入 FP ?
• Reference
Outline
• FP 是 Paradigm, 不是 Pattern 也不是 Framework,
更不是 Language
• 是一種以 Function 為中心的 「思考方式」與 「程
式風格」
• 有別於目前主流 OOP,比較冷門,但不代表你不認
識他
Introduction
其實我們天天在用的 LINQ,就是 FP
• LINQ 的 IEnumerable 提供了大量的 Operator
• 我們只需為客製化部分提供 Lambda 即可
LINQ
Range(1, 3)
.Select(x => x + 1)
.OrderBy(x => -x)
.ToList()
.ForEach(WriteLine);
4
3
2
Definition
• 在數學裡,function 就是 x 與 y = f(x) 的對應關係
• f(x) 結果只與 x 的輸入有關,不會其他任何東西相關
Mathematical Function
• Domain : 所有 x 稱為 定義域
• Codomain : 所有可能的 f(x) 稱為 對應域
• Range : 所有實際的 f(x) 稱為 值域
Mathematical Function
代數
國中就學過了
FP
• 將 Mathematical Function 以 code 呈現,稱為 Pure
Function
• Pure Function : function 的結果只與參數有關,不會
與其他任何東西相關
Pure Function
int Foo(int x)
{
return x + 1;
}
• Func() 的結果會與參數以外的資料相關 => 非 Pure
Function
• z 的改變可能影響到其他 function (Side Effect)
• w 的改變可能影響 Func() (Side Effect)
Programming Function
int z = 1;
int w = 0;
int Foo(int x)
{
w = 3;
return 2 * x + z + 3;
}
Debug 大都在釐清 Side Effect
• 修改 Function 外部的變數
• 修改 Function 的 input 參數
• 拋出 Exception
• 處理 I/O
Side Effect
• Function as Data / Higher Order Functions
• No State Mutation
Functional Programming
• First-Class Function
• 能將 Function 指定給變數 (Delegate)
• 能將 Function 傳進 Function (Higher Order Function)
• 能使 Function 回傳 Function (Higher Order Function)
• 能將 Function 存進 Collection
Function as Data
C# 是以 Delegate 為基礎的 FP
• 將 Lambda 指定給 Triple Delegate
• Func<int, string> : 輸入為 int,回傳為 string
能將 Function 指定給變數 (Delegate)
Func<int, int> Triple = x => x * 3;
Range(1, 3)
.Select(Triple)
.OrderBy(x => -x)
.ToList()
.ForEach(WriteLine);
9
6
3
• 定義 Triple() Local Function
• Triple() 會自動轉成 Delegate 傳入 Select()
• Select() 為 Higher Order Function
能將 Function 傳進 Function
int Triple(int x) => x * 3;
Range(1, 3)
.Select(Triple)
.OrderBy(x => -x)
.ToList()
.ForEach(WriteLine);
9
6
3
• 將 3 也變成參數
• Triple(3) 回傳的是 Function (Delegate)
• Tripe() 為 Higher Order Function
能使 Function 回傳 Function
Func<int, Func<int,int>> Triple = x => y => x * y;
Range(1, 3)
.Select(Triple(3))
.OrderBy(x => -x)
.ToList()
.ForEach(WriteLine);
9
6
3
• 使用 Dictionary 實現 Function Factory
能將 Function 存進 Collection
var lut = new Dictionary<char, Func<int, int>> {
{'+', x => x + x},
{'*', x => x * x}
};
Range(1, 3).
.Select(lut[ '*' ])
.ToList()
.ForEach(WriteLine);
1
4
9
資料不能修改,只能建立新的
(Immutable)
No State Mutation
Mutable
public class Rectangle
{
public int Length { get; set; }
public int Height { get; set; }
public void Grow(int length, int height)
{
Length += length;
Height += height;
}
}
Rectangle r1 = new Rectangle {
Length = 5, Height = 10
};
r1.Grow(10, 10); 15; 20
Immutable
public class Rectangle
{
public int Length { get; }
public int Height { get; }
public Rectangle(int length, int height)
{
Length = length;
Height = height;
}
public Rectangle Grow(int length, int height)
=> new Rectangle(Length + length, Height + height);
}
Rectangle r1 = new Rectangle(5, 10);
var r2 = r1.Grow(10, 10);
15; 20
• Sort() 直接對 data 做排序,修改原本資料
• Sort() 為 void,無法繼續串下去
Mutable
var data = new List<int> { 3, 2, 1 };
data.Sort();
data.ForEach(WriteLine);
1
2
3
• OrderBy() 沒有宣改原本 data,而是建立新的 data
Immutable
var data = new List<int> { 3, 2, 1 };
data
.OrderBy(item => item)
.ToList()
.ForEach(WriteLine);
1
2
3
• 每次執行結果都不一樣 (Race Condition)
Parallel Computation (Mutable)
var data = Range(-10000, 20001).Reverse().ToList();
Action task1 = () => WriteLine(data.Sum());
Action task2 = () => { data.Sort(); WriteLine(data.Sum()); };
Parallel.Invoke(task1, task2);
• 每次執行結果都一樣
• 沒有 Race Condition
Parallel Computation (Immutable)
var data = Range(-10000, 20001).Reverse().ToList();
Action task1 = () => WriteLine(data.Sum());
Action task2 = () => WriteLine(data.OrderBy(x => x).Sum());
Parallel.Invoke(task1, task2);
• 只要加上 AsParallel(),完全無痛升級多核心運算
Parallel Computation (Immutable)
int Triple(int x) => x *3 ;
Range(1, 100)
.AsParallel()
.Select(Triple)
.OrderBy(x => x)
.ToList()
.ForEach(WriteLine);
FP 不斷地建立新資料,執行速度 OK 嗎 ?
• Lazy Evaluation : 程式碼不會立即執行,等到有需求時
才執行
• Yield : 避免在 Function 傳遞之間不斷重新建立 Data
Lazy Evaluation 與 Yield
• 需要不斷建立 result,然後回傳,執行效率差
LINQ Select 非 FP 作法
public static IEnumerable<U> Select<T, U>(this
IEnumerable<T> data, Func<T, U> fn)
{
var result = new List<U>();
foreach (var item in list)
{
result.Add(fn(item));
}
return result;
}
• 直到 WriteLine 執行時,才會執行 fn(item) 回傳
LINQ Select FP 作法
public static IEnumerable<U> Select<T, U>(this
IEnumerable<T> data, Func<T, U> fn)
{
foreach (var item in list)
{
yield return fn(item));
}
}
FP 文藝復興
• 單核心無法超越 5GHz,改成多核心設計
• Side Effect 難寫 Unit Test
• OOP 造成 Interface 爆炸
• Reactive Programming 崛起
• 雲端 Stateless (Azure Function / AWS Lambda)
FP 文藝復興
使用 FP 的公司
OOP vs. FP
OOP 與 FP 比較表
OOP FP
Encapsulation
Data 與 Logic 包在
class 內
Data 與 Logic 分家
State Mutation Mutable Immutable
Modularity Class Function
Dependency IoC Container Higher Order Function
Loose Coupling Interface Signature
C# 對 FP 支援
• 1.0
• Delegate
• 3.0
• Func、Action
• Lambda
• LINQ
• Extension Method
• 6.0
• Using Static
• Expression Body
• Getter Only Property
• 7.0 ~ 7.3
• Local Function
• Tuple
• Pattern Matching
• Expression Body
C# 版本進化 - FP 支援度
• Record Type
• 更完整 Pattern Matching
• 更完整 Tuple
C# 8.0
如何學習與導入 FP ?
• Step 1 : 多使用 LINQ 處理 Data,少自己硬幹
• Step 2 : 將 Data 與 Function 分離,為 Data 型別寫
Extension Method
• Step 3 : 將 Side Effect 部分隔離在 Data Flow 前後
學習 FP
Functinal Programming in C#
Enrico Buonanno
August, 2017
ISBN : 9781617293955
Manning
• 全書以 C# 6/7 為範例
• 將抽象的概念使用易懂的文字
與圖片介紹
• 手把手建立一個 FP Library,
彌補目前 C# 還沒支援的功能
(Option、Either…)
• 以後端的角度介紹 FP,範例
貼近實務
• OOP x FP
• Pure FP
導入 FP
• Channel 9, Functional Programming in C#
• NDC, Functional Techniques for C#
• NDC, C# 8
• NDC, Logic vs. Side Effects : Functional Godness you
don’t hear about
Reference
特別感謝

More Related Content

What's hot

Laravel - 系統全攻略
Laravel - 系統全攻略Laravel - 系統全攻略
Laravel - 系統全攻略
Vincent Chi
 
CRUD 綜合運用
CRUD 綜合運用CRUD 綜合運用
CRUD 綜合運用
Shengyou Fan
 
進擊的前端工程師:今天就用 JSON Server 自己打造 API 吧!
進擊的前端工程師:今天就用 JSON Server 自己打造 API 吧!進擊的前端工程師:今天就用 JSON Server 自己打造 API 吧!
進擊的前端工程師:今天就用 JSON Server 自己打造 API 吧!
Will Huang
 
Eloquent ORM
Eloquent ORMEloquent ORM
Eloquent ORM
Shengyou Fan
 
Migrations 與 Schema 操作
Migrations 與 Schema 操作Migrations 與 Schema 操作
Migrations 與 Schema 操作
Shengyou Fan
 
Eloquent ORM
Eloquent ORMEloquent ORM
Eloquent ORM
Shengyou Fan
 
驗證與訊息
驗證與訊息驗證與訊息
驗證與訊息
Shengyou Fan
 
整合 Open ID
整合 Open ID整合 Open ID
整合 Open ID
Shengyou Fan
 
CRUD 綜合運用
CRUD 綜合運用CRUD 綜合運用
CRUD 綜合運用
Shengyou Fan
 
Angular 2 Taiwan 小聚 Forms 介紹
Angular 2 Taiwan 小聚 Forms 介紹Angular 2 Taiwan 小聚 Forms 介紹
Angular 2 Taiwan 小聚 Forms 介紹
Jeff Wu
 
Asp.net core v1.0
Asp.net core v1.0Asp.net core v1.0
Asp.net core v1.0
chang kuo-chao
 
Angular 2 表單的處理與驗證
Angular 2 表單的處理與驗證Angular 2 表單的處理與驗證
Angular 2 表單的處理與驗證
Jeff Wu
 
HTML 語法教學
HTML 語法教學HTML 語法教學
HTML 語法教學
Shengyou Fan
 
開發環境建置
開發環境建置開發環境建置
開發環境建置
Shengyou Fan
 
DAE
DAEDAE
View 與 Blade 樣板引擎
View 與 Blade 樣板引擎View 與 Blade 樣板引擎
View 與 Blade 樣板引擎
Shengyou Fan
 
工作坊總結
工作坊總結工作坊總結
工作坊總結
Shengyou Fan
 
使用 Controller
使用 Controller使用 Controller
使用 Controller
Shengyou Fan
 
Package 安裝與使用
Package 安裝與使用Package 安裝與使用
Package 安裝與使用
Shengyou Fan
 
使用 Controller
使用 Controller使用 Controller
使用 Controller
Shengyou Fan
 

What's hot (20)

Laravel - 系統全攻略
Laravel - 系統全攻略Laravel - 系統全攻略
Laravel - 系統全攻略
 
CRUD 綜合運用
CRUD 綜合運用CRUD 綜合運用
CRUD 綜合運用
 
進擊的前端工程師:今天就用 JSON Server 自己打造 API 吧!
進擊的前端工程師:今天就用 JSON Server 自己打造 API 吧!進擊的前端工程師:今天就用 JSON Server 自己打造 API 吧!
進擊的前端工程師:今天就用 JSON Server 自己打造 API 吧!
 
Eloquent ORM
Eloquent ORMEloquent ORM
Eloquent ORM
 
Migrations 與 Schema 操作
Migrations 與 Schema 操作Migrations 與 Schema 操作
Migrations 與 Schema 操作
 
Eloquent ORM
Eloquent ORMEloquent ORM
Eloquent ORM
 
驗證與訊息
驗證與訊息驗證與訊息
驗證與訊息
 
整合 Open ID
整合 Open ID整合 Open ID
整合 Open ID
 
CRUD 綜合運用
CRUD 綜合運用CRUD 綜合運用
CRUD 綜合運用
 
Angular 2 Taiwan 小聚 Forms 介紹
Angular 2 Taiwan 小聚 Forms 介紹Angular 2 Taiwan 小聚 Forms 介紹
Angular 2 Taiwan 小聚 Forms 介紹
 
Asp.net core v1.0
Asp.net core v1.0Asp.net core v1.0
Asp.net core v1.0
 
Angular 2 表單的處理與驗證
Angular 2 表單的處理與驗證Angular 2 表單的處理與驗證
Angular 2 表單的處理與驗證
 
HTML 語法教學
HTML 語法教學HTML 語法教學
HTML 語法教學
 
開發環境建置
開發環境建置開發環境建置
開發環境建置
 
DAE
DAEDAE
DAE
 
View 與 Blade 樣板引擎
View 與 Blade 樣板引擎View 與 Blade 樣板引擎
View 與 Blade 樣板引擎
 
工作坊總結
工作坊總結工作坊總結
工作坊總結
 
使用 Controller
使用 Controller使用 Controller
使用 Controller
 
Package 安裝與使用
Package 安裝與使用Package 安裝與使用
Package 安裝與使用
 
使用 Controller
使用 Controller使用 Controller
使用 Controller
 

Similar to Study4.TW .NET Conf 2018 - Fp in c#

The Evolution of Async Programming (GZ TechParty C#)
The Evolution of Async Programming (GZ TechParty C#)The Evolution of Async Programming (GZ TechParty C#)
The Evolution of Async Programming (GZ TechParty C#)jeffz
 
Java8 lambda
Java8 lambdaJava8 lambda
Java8 lambdakoji lin
 
Angular 开发技巧 (2018 ngChina 开发者大会)
Angular 开发技巧 (2018 ngChina 开发者大会)Angular 开发技巧 (2018 ngChina 开发者大会)
Angular 开发技巧 (2018 ngChina 开发者大会)
Will Huang
 
Java SE 8 的 Lambda 連鎖效應 - 語法、風格與程式庫
Java SE 8 的 Lambda 連鎖效應 - 語法、風格與程式庫Java SE 8 的 Lambda 連鎖效應 - 語法、風格與程式庫
Java SE 8 的 Lambda 連鎖效應 - 語法、風格與程式庫
Justin Lin
 
Python速成指南
Python速成指南Python速成指南
Python速成指南
March Liu
 
12, string
12, string12, string
12, string
ted-xu
 
02.python基础
02.python基础02.python基础
02.python基础
modou li
 
functional-scala
functional-scalafunctional-scala
functional-scala
wang hongjiang
 
Python 温故
Python 温故Python 温故
Python 温故
勇浩 赖
 
Hands on data analysis 101
Hands on data analysis 101Hands on data analysis 101
Hands on data analysis 101
FEG
 
Python 入門
Python 入門 Python 入門
Python 入門
Andy Yao
 
Java 開發者的函數式程式設計
Java 開發者的函數式程式設計Java 開發者的函數式程式設計
Java 開發者的函數式程式設計
Justin Lin
 
iOS中Lua脚本的应用
iOS中Lua脚本的应用iOS中Lua脚本的应用
iOS中Lua脚本的应用
Proteas Wang
 
Ecma script edition5-小试
Ecma script edition5-小试Ecma script edition5-小试
Ecma script edition5-小试lydiafly
 
走马观花— Haskell Web 开发
走马观花— Haskell Web 开发走马观花— Haskell Web 开发
走马观花— Haskell Web 开发
Gump Law
 
模块一-Go语言特性.pdf
模块一-Go语言特性.pdf模块一-Go语言特性.pdf
模块一-Go语言特性.pdf
czzz1
 
twMVC#46_SQL Server 資料分析大躍進 Machine Learning Services
twMVC#46_SQL Server 資料分析大躍進 Machine Learning ServicestwMVC#46_SQL Server 資料分析大躍進 Machine Learning Services
twMVC#46_SQL Server 資料分析大躍進 Machine Learning Services
twMVC
 

Similar to Study4.TW .NET Conf 2018 - Fp in c# (20)

The Evolution of Async Programming (GZ TechParty C#)
The Evolution of Async Programming (GZ TechParty C#)The Evolution of Async Programming (GZ TechParty C#)
The Evolution of Async Programming (GZ TechParty C#)
 
Java8 lambda
Java8 lambdaJava8 lambda
Java8 lambda
 
Angular 开发技巧 (2018 ngChina 开发者大会)
Angular 开发技巧 (2018 ngChina 开发者大会)Angular 开发技巧 (2018 ngChina 开发者大会)
Angular 开发技巧 (2018 ngChina 开发者大会)
 
LabView with Lego NXT
LabView  with Lego NXTLabView  with Lego NXT
LabView with Lego NXT
 
Java SE 8 的 Lambda 連鎖效應 - 語法、風格與程式庫
Java SE 8 的 Lambda 連鎖效應 - 語法、風格與程式庫Java SE 8 的 Lambda 連鎖效應 - 語法、風格與程式庫
Java SE 8 的 Lambda 連鎖效應 - 語法、風格與程式庫
 
Python速成指南
Python速成指南Python速成指南
Python速成指南
 
12, string
12, string12, string
12, string
 
02.python基础
02.python基础02.python基础
02.python基础
 
functional-scala
functional-scalafunctional-scala
functional-scala
 
Python 温故
Python 温故Python 温故
Python 温故
 
Hands on data analysis 101
Hands on data analysis 101Hands on data analysis 101
Hands on data analysis 101
 
Python 入門
Python 入門 Python 入門
Python 入門
 
getPDF.aspx
getPDF.aspxgetPDF.aspx
getPDF.aspx
 
getPDF.aspx
getPDF.aspxgetPDF.aspx
getPDF.aspx
 
Java 開發者的函數式程式設計
Java 開發者的函數式程式設計Java 開發者的函數式程式設計
Java 開發者的函數式程式設計
 
iOS中Lua脚本的应用
iOS中Lua脚本的应用iOS中Lua脚本的应用
iOS中Lua脚本的应用
 
Ecma script edition5-小试
Ecma script edition5-小试Ecma script edition5-小试
Ecma script edition5-小试
 
走马观花— Haskell Web 开发
走马观花— Haskell Web 开发走马观花— Haskell Web 开发
走马观花— Haskell Web 开发
 
模块一-Go语言特性.pdf
模块一-Go语言特性.pdf模块一-Go语言特性.pdf
模块一-Go语言特性.pdf
 
twMVC#46_SQL Server 資料分析大躍進 Machine Learning Services
twMVC#46_SQL Server 資料分析大躍進 Machine Learning ServicestwMVC#46_SQL Server 資料分析大躍進 Machine Learning Services
twMVC#46_SQL Server 資料分析大躍進 Machine Learning Services
 

More from Chieh Kai Yang

Dotnet Conf 2021 - F# and Safe Stack
Dotnet Conf 2021 - F# and Safe StackDotnet Conf 2021 - F# and Safe Stack
Dotnet Conf 2021 - F# and Safe Stack
Chieh Kai Yang
 
無密碼時代終於要來了嗎
無密碼時代終於要來了嗎無密碼時代終於要來了嗎
無密碼時代終於要來了嗎
Chieh Kai Yang
 
Structured data
Structured dataStructured data
Structured data
Chieh Kai Yang
 
Web.dev extended : What's new in Web [GDG Taichung]
Web.dev extended : What's new in Web [GDG Taichung]Web.dev extended : What's new in Web [GDG Taichung]
Web.dev extended : What's new in Web [GDG Taichung]
Chieh Kai Yang
 
Study4TW - .NET Conf 2019 - Rx
Study4TW - .NET Conf 2019 - RxStudy4TW - .NET Conf 2019 - Rx
Study4TW - .NET Conf 2019 - Rx
Chieh Kai Yang
 
Reactive Programmin
Reactive ProgramminReactive Programmin
Reactive Programmin
Chieh Kai Yang
 
從零走到 Angular 世界
從零走到 Angular 世界從零走到 Angular 世界
從零走到 Angular 世界
Chieh Kai Yang
 
How to 系列 - Hosting a website
How to 系列 - Hosting a websiteHow to 系列 - Hosting a website
How to 系列 - Hosting a website
Chieh Kai Yang
 
2018-01-06 Study4Love Conference - Rendertron
2018-01-06 Study4Love Conference - Rendertron2018-01-06 Study4Love Conference - Rendertron
2018-01-06 Study4Love Conference - Rendertron
Chieh Kai Yang
 
ModernWeb 2017 angular component
ModernWeb 2017 angular componentModernWeb 2017 angular component
ModernWeb 2017 angular component
Chieh Kai Yang
 

More from Chieh Kai Yang (10)

Dotnet Conf 2021 - F# and Safe Stack
Dotnet Conf 2021 - F# and Safe StackDotnet Conf 2021 - F# and Safe Stack
Dotnet Conf 2021 - F# and Safe Stack
 
無密碼時代終於要來了嗎
無密碼時代終於要來了嗎無密碼時代終於要來了嗎
無密碼時代終於要來了嗎
 
Structured data
Structured dataStructured data
Structured data
 
Web.dev extended : What's new in Web [GDG Taichung]
Web.dev extended : What's new in Web [GDG Taichung]Web.dev extended : What's new in Web [GDG Taichung]
Web.dev extended : What's new in Web [GDG Taichung]
 
Study4TW - .NET Conf 2019 - Rx
Study4TW - .NET Conf 2019 - RxStudy4TW - .NET Conf 2019 - Rx
Study4TW - .NET Conf 2019 - Rx
 
Reactive Programmin
Reactive ProgramminReactive Programmin
Reactive Programmin
 
從零走到 Angular 世界
從零走到 Angular 世界從零走到 Angular 世界
從零走到 Angular 世界
 
How to 系列 - Hosting a website
How to 系列 - Hosting a websiteHow to 系列 - Hosting a website
How to 系列 - Hosting a website
 
2018-01-06 Study4Love Conference - Rendertron
2018-01-06 Study4Love Conference - Rendertron2018-01-06 Study4Love Conference - Rendertron
2018-01-06 Study4Love Conference - Rendertron
 
ModernWeb 2017 angular component
ModernWeb 2017 angular componentModernWeb 2017 angular component
ModernWeb 2017 angular component
 

Study4.TW .NET Conf 2018 - Fp in c#

  • 2. Introducing Functional Programming in C# Kevin Yang, Sam Xiao
  • 3. • Angular Taiwan、Angular Girls Taiwan 、TypeScript Taiwan 社群管理 者 • Angular 線上讀書會主持人 • Angular/Web GDE (Google Developer Expert) 開發專家 • 微軟最有價值專家(Visual Studio and Development Technologies)。 • 部落格:https://blog.kevinyang.net/ • FB粉絲頁:https://www.facebook.com/CKNotepad/ About Kevin
  • 4. • Laravel 台中社群小聚 2016 講師 • Community Open Camp 2016 講師 • PHPConf 2016 講師 • COSCUP 2017 講師 • Angular 台北社群小聚 2017 講師 • 微軟最有價值專家(Visual Studio and Development Technologies) • 部落格:點燈坊 • FB 粉絲頁 : 點燈坊 About Sam
  • 5. • Introduction • Definition • FP 文藝復興 • OOP vs. FP • C# 對 FP 支援 • 如何學習與導入 FP ? • Reference Outline
  • 6. • FP 是 Paradigm, 不是 Pattern 也不是 Framework, 更不是 Language • 是一種以 Function 為中心的 「思考方式」與 「程 式風格」 • 有別於目前主流 OOP,比較冷門,但不代表你不認 識他 Introduction
  • 8. • LINQ 的 IEnumerable 提供了大量的 Operator • 我們只需為客製化部分提供 Lambda 即可 LINQ Range(1, 3) .Select(x => x + 1) .OrderBy(x => -x) .ToList() .ForEach(WriteLine); 4 3 2
  • 10. • 在數學裡,function 就是 x 與 y = f(x) 的對應關係 • f(x) 結果只與 x 的輸入有關,不會其他任何東西相關 Mathematical Function
  • 11. • Domain : 所有 x 稱為 定義域 • Codomain : 所有可能的 f(x) 稱為 對應域 • Range : 所有實際的 f(x) 稱為 值域 Mathematical Function
  • 13. FP
  • 14. • 將 Mathematical Function 以 code 呈現,稱為 Pure Function • Pure Function : function 的結果只與參數有關,不會 與其他任何東西相關 Pure Function int Foo(int x) { return x + 1; }
  • 15. • Func() 的結果會與參數以外的資料相關 => 非 Pure Function • z 的改變可能影響到其他 function (Side Effect) • w 的改變可能影響 Func() (Side Effect) Programming Function int z = 1; int w = 0; int Foo(int x) { w = 3; return 2 * x + z + 3; }
  • 17. • 修改 Function 外部的變數 • 修改 Function 的 input 參數 • 拋出 Exception • 處理 I/O Side Effect
  • 18. • Function as Data / Higher Order Functions • No State Mutation Functional Programming
  • 19. • First-Class Function • 能將 Function 指定給變數 (Delegate) • 能將 Function 傳進 Function (Higher Order Function) • 能使 Function 回傳 Function (Higher Order Function) • 能將 Function 存進 Collection Function as Data
  • 20. C# 是以 Delegate 為基礎的 FP
  • 21. • 將 Lambda 指定給 Triple Delegate • Func<int, string> : 輸入為 int,回傳為 string 能將 Function 指定給變數 (Delegate) Func<int, int> Triple = x => x * 3; Range(1, 3) .Select(Triple) .OrderBy(x => -x) .ToList() .ForEach(WriteLine); 9 6 3
  • 22. • 定義 Triple() Local Function • Triple() 會自動轉成 Delegate 傳入 Select() • Select() 為 Higher Order Function 能將 Function 傳進 Function int Triple(int x) => x * 3; Range(1, 3) .Select(Triple) .OrderBy(x => -x) .ToList() .ForEach(WriteLine); 9 6 3
  • 23. • 將 3 也變成參數 • Triple(3) 回傳的是 Function (Delegate) • Tripe() 為 Higher Order Function 能使 Function 回傳 Function Func<int, Func<int,int>> Triple = x => y => x * y; Range(1, 3) .Select(Triple(3)) .OrderBy(x => -x) .ToList() .ForEach(WriteLine); 9 6 3
  • 24. • 使用 Dictionary 實現 Function Factory 能將 Function 存進 Collection var lut = new Dictionary<char, Func<int, int>> { {'+', x => x + x}, {'*', x => x * x} }; Range(1, 3). .Select(lut[ '*' ]) .ToList() .ForEach(WriteLine); 1 4 9
  • 26. Mutable public class Rectangle { public int Length { get; set; } public int Height { get; set; } public void Grow(int length, int height) { Length += length; Height += height; } } Rectangle r1 = new Rectangle { Length = 5, Height = 10 }; r1.Grow(10, 10); 15; 20
  • 27. Immutable public class Rectangle { public int Length { get; } public int Height { get; } public Rectangle(int length, int height) { Length = length; Height = height; } public Rectangle Grow(int length, int height) => new Rectangle(Length + length, Height + height); } Rectangle r1 = new Rectangle(5, 10); var r2 = r1.Grow(10, 10); 15; 20
  • 28. • Sort() 直接對 data 做排序,修改原本資料 • Sort() 為 void,無法繼續串下去 Mutable var data = new List<int> { 3, 2, 1 }; data.Sort(); data.ForEach(WriteLine); 1 2 3
  • 29. • OrderBy() 沒有宣改原本 data,而是建立新的 data Immutable var data = new List<int> { 3, 2, 1 }; data .OrderBy(item => item) .ToList() .ForEach(WriteLine); 1 2 3
  • 30. • 每次執行結果都不一樣 (Race Condition) Parallel Computation (Mutable) var data = Range(-10000, 20001).Reverse().ToList(); Action task1 = () => WriteLine(data.Sum()); Action task2 = () => { data.Sort(); WriteLine(data.Sum()); }; Parallel.Invoke(task1, task2);
  • 31. • 每次執行結果都一樣 • 沒有 Race Condition Parallel Computation (Immutable) var data = Range(-10000, 20001).Reverse().ToList(); Action task1 = () => WriteLine(data.Sum()); Action task2 = () => WriteLine(data.OrderBy(x => x).Sum()); Parallel.Invoke(task1, task2);
  • 32. • 只要加上 AsParallel(),完全無痛升級多核心運算 Parallel Computation (Immutable) int Triple(int x) => x *3 ; Range(1, 100) .AsParallel() .Select(Triple) .OrderBy(x => x) .ToList() .ForEach(WriteLine);
  • 34. • Lazy Evaluation : 程式碼不會立即執行,等到有需求時 才執行 • Yield : 避免在 Function 傳遞之間不斷重新建立 Data Lazy Evaluation 與 Yield
  • 35. • 需要不斷建立 result,然後回傳,執行效率差 LINQ Select 非 FP 作法 public static IEnumerable<U> Select<T, U>(this IEnumerable<T> data, Func<T, U> fn) { var result = new List<U>(); foreach (var item in list) { result.Add(fn(item)); } return result; }
  • 36. • 直到 WriteLine 執行時,才會執行 fn(item) 回傳 LINQ Select FP 作法 public static IEnumerable<U> Select<T, U>(this IEnumerable<T> data, Func<T, U> fn) { foreach (var item in list) { yield return fn(item)); } }
  • 38. • 單核心無法超越 5GHz,改成多核心設計 • Side Effect 難寫 Unit Test • OOP 造成 Interface 爆炸 • Reactive Programming 崛起 • 雲端 Stateless (Azure Function / AWS Lambda) FP 文藝復興
  • 41. OOP 與 FP 比較表 OOP FP Encapsulation Data 與 Logic 包在 class 內 Data 與 Logic 分家 State Mutation Mutable Immutable Modularity Class Function Dependency IoC Container Higher Order Function Loose Coupling Interface Signature
  • 42. C# 對 FP 支援
  • 43. • 1.0 • Delegate • 3.0 • Func、Action • Lambda • LINQ • Extension Method • 6.0 • Using Static • Expression Body • Getter Only Property • 7.0 ~ 7.3 • Local Function • Tuple • Pattern Matching • Expression Body C# 版本進化 - FP 支援度
  • 44. • Record Type • 更完整 Pattern Matching • 更完整 Tuple C# 8.0
  • 46. • Step 1 : 多使用 LINQ 處理 Data,少自己硬幹 • Step 2 : 將 Data 與 Function 分離,為 Data 型別寫 Extension Method • Step 3 : 將 Side Effect 部分隔離在 Data Flow 前後 學習 FP
  • 47. Functinal Programming in C# Enrico Buonanno August, 2017 ISBN : 9781617293955 Manning • 全書以 C# 6/7 為範例 • 將抽象的概念使用易懂的文字 與圖片介紹 • 手把手建立一個 FP Library, 彌補目前 C# 還沒支援的功能 (Option、Either…) • 以後端的角度介紹 FP,範例 貼近實務
  • 48. • OOP x FP • Pure FP 導入 FP
  • 49. • Channel 9, Functional Programming in C# • NDC, Functional Techniques for C# • NDC, C# 8 • NDC, Logic vs. Side Effects : Functional Godness you don’t hear about Reference

Editor's Notes

  1. Kevin
  2. Kevin
  3. Kevin
  4. Kevin
  5. Sam
  6. Sam
  7. Sam
  8. Kevin
  9. Kevin
  10. Kevin
  11. Kevin
  12. Kevin
  13. Kevin
  14. Kevin
  15. Sam
  16. Sam
  17. Sam
  18. Sam
  19. Sam
  20. Sam (30 m)
  21. Kevin
  22. Kevin
  23. Kevin
  24. Kevin
  25. Kevin ParallelMutable
  26. Kevin ParallelImmutable
  27. Kevin PLINQ
  28. Sam
  29. Sam
  30. Kevin
  31. Kevin
  32. Sam
  33. Sam & Kevin
  34. Kevin
  35. Sam & Kevin
  36. Kevin
  37. Sam & Kevin