
Functional Programming in Python筆記 Part 1: (Avoid) Flow Control
學了scala後,想多用high-order function。看完oreilly這本書後,現在蠻常用在python裡用fp的寫法,以下把照各章節順序整理有用的資訊,並加上自己的心得
(以下python code縮排有些變成8格, gist 一直改不過來,放棄惹)
(Avoid) Flow Control
寫code應該要注重what不是how.
-Encapsulation
把有用的code包裝成function讓別人可以call
-Comprehension
not comprehension V.S. comprehension
-Comprehension:Generators
function_based_generators V.S. class_based_generators V.S. comprehension
- Comprehension:Dicts and Sets
一樣可以用comprehension,如下
結論: Comprehension好棒棒,好懂code又短。常用的filter可以用comprehension寫
Recursion
由於python沒有tail recursion的設計,預設最大recursion是1000. 像是用scala可以寫出如下的factorial(在Intellj IDEA scala worksheet的結果,前面加上@tailrec可以強迫IDE去檢查), 即使 數字很大, stack也不會爆炸, 因為最後回傳值只有一個值, compiler會自動把stack回收
書上用python寫的版本
作者覺得python中factorial跑最快的FP寫法(後面章節才會說reduce):
作者說一般不建議在python裡寫recursion, 效能太不好
-Eliminating Loops
把所有for-loop能做的事都用map這函數做掉,作者說只是好玩,後面章節有更詳細介紹map. (map return 一個generator, 用過一次就不見了)
Comment…