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

PPTX
改善 Angular 開發流程:你所不知道的 Schematics 程式碼產生器
PDF
使用 Eloquent ORM
PDF
Schema & Migration操作
PDF
開發流程與工具介紹
PPT
Underscore
PDF
Model & Seeding整合
PPTX
Angular 7 全新功能探索 (Angular Taiwan 2018)
PDF
Migrations 與 Schema操作
改善 Angular 開發流程:你所不知道的 Schematics 程式碼產生器
使用 Eloquent ORM
Schema & Migration操作
開發流程與工具介紹
Underscore
Model & Seeding整合
Angular 7 全新功能探索 (Angular Taiwan 2018)
Migrations 與 Schema操作

What's hot (20)

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

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

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

More from Chieh Kai Yang (10)

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