More Related Content Similar to 那些函數語言Tutorial沒有教我的事 Similar to 那些函數語言Tutorial沒有教我的事 (14) 那些函數語言Tutorial沒有教我的事2. About me
• 大貓, YC Ling, @miaout17
– 感冒中,聲音有點啞請見諒 m(_ _)m
• Game developer, 2007~2010
• Web (backend) developer, 2010~now
• http://about.me/miaout17
4. The Next Mainstream Programming Language:
A Game Developer’s Perspective (2006)
Tim Sweeney, CEO of Epic Games
6. Really?
First result of Google “functional programming concurrent”…
http://www.quora.com/Why-does-functional-programming-favor-concurrency
No Side
Effect
Functional
Multi-Core Concurrency
Programming
Immutable
Data
7. Outline
• 函數語言的各種特性
• Pure Function & Side Effect
• Immutable Data Structure
• Conclusion
9. 函數語言的各種特性
Higher-Order Function Partial
Function Composition Application
Lisp, Scheme
Erlang, Haskell, Clojure, Scala First-Class
Perl, Ruby, Python, JavaScript Function
C++11, C#3.0, Java8…
Functional Immutable
Programming Data Structure
Monad
Haskell, Erlang…
Haskell… Single
Category Pure
Assignment
Functional
Haskell…
Arrow
No Side
Effect
12. Pure Function - C++
C++: Impure Function C++: Pure Function
Output:
1
2
6
24
120…
13. Pure Function – Erlang
Single Assignment
Impure
print_factorical(5, 1, 1) 1
print_factorical(5, 2, 1) 2
print_factorical(5, 3, 2) 6
print_factorical(5, 4, 6) 24
print_factorical(5, 5, 24) 120
Pure
gen(5, 1, 1, [])
=gen(5, 2, 1, [1])
=gen(5, 3, 2, [2, 1])
=gen(5, 4, 6, [6, 2, 1])
=gen(5, 5, 24, [24, 6, 2, 1])
=[120, 24, 6, 2, 1]
15. Side Effect & Pure Function – 小結
• 函數語言沒有副作用?
– 命題沒有意義。所有程式都有副作用。
• 函數語言中,所有函數都是純函數?
– 大多數的函數語言無法保證函數是純函數。(Ex. Lisp, Scheme, Scala…)
– 少數語言有單一賦值特性,可避免廣域變數造成副作用。
(Ex. Haskell, Erlang…)
– 少數語言可用型別系統區別純函數與非純函數。(Ex. Haskell…)
• 使用函數語言就不用擔心副作用的問題了(X)
• 學習函數語言的編程典範,能對純函數、副作用
等概念有更透徹的理解 (O)
19. Immutable Data Structure – 小結
• 函數語言中,資料都是不可變(Immutable)的?
– 只有Haskell, Erlang等少數語言保證資料結構不可變。
• 如何確保資料結構不可變?
– 語言保證所有資料結構皆不可變 (Ex. Haskell, Erlang)
– 將特定資料結構宣告為不可變 (Ex. Scala, Java, C++…)
– 約定與紀律
• 使用函數語言,就不必擔心平行程式中,共享可
變狀態的問題了 (X)
• 學習函數語言的編程典範,能對純函數、不可變
資料等概念有更透徹的理解 (O)
20. Conclusion
• 現今「函數語言」其實是指很多具有不同特性
的語言,很難一言概括分析。
• 分析語言帶來的好處,應該逐一分析
– 語言特性帶來的優點(及其代價)
– 編程典範帶來的優點
• 函數語言不是並行、平行程式的萬靈丹,但其
編程典範相當適合並行、平行程式。
• 不要輕易相信或否定他人的說法
– 試著獨立思考、驗證這些說法