Functional Python Programming - ch[01]

Learning notes on Functional Python Programming

  • Book: Functional Python Programming
  • Chapter: Introducing Functional Programming

Functional programming and Imperative programming

  • python is an imperative programming language, which indicates which indicates the state of computation is reflected by the variables in various namespaces.

    • Like concept of "Everything is a file" in UNIX world, for imperative languages "Every state is a snapshot of variables"
    • Like the pipeline/redirection/filter concepts in UNIX, the program will always focus on states of variables, the program is nothing more then a pipeline connected filter(algorithm) collections, which may try to redirect the input data to the target output data
  • python also holds some functional programming features

    • In functional programming, the states of variables were being replaced by function evaluations, each evaluation will create a new object from the current object
    • As the program is a collection of functions, it is very similar to the solving procedures in Math, we can make easy functions, then regroup them by iteration or recusion to achieve complex functions
  • Comparison among different models in imperative programming: Procedural and OO

    • Procedural: procudural model will treate the data as a stream, everything will be built around the stream, the state of the program is defined by variables
    • OO: The state of the program is also determined by variables
# example Procedural
count=0
for idx in range(0,11):
    if idx % 3 == 0 or count % 5 == 0:
        count += 1

# example OO
count=0
tgtList=list()
for idx in range(0,11):
    if idx % 3 == 0 or count % 5 == 0:
        tgtList.append(idx)
sum(tgtList);

# Another OO example: a class with a method sum
class sum_list(list):
    def sum(self):
        s = 0
        for v in self.__iter__():
            s += v
        return s
  • Functional Paradigm
    • To calc the sum of the multiples of 3 and 5 can be defined in two parts:
      • The sum of a sequence of numbers
      • The number for sum must pass a simple test to be selected
# A resursive sum function
def sum(sequence):
    if len(sequence) == 0:
        return 0
    return sequence[0]+sum(sequence[1:])
sum([x for x in range(1,11)]);

In the last case, the sum function is being transformed into a "divide-calc-merge" function, first divide the funtion into parts, where all parts follow a same pattern then calc it by recursion, at last merge the result at the final dest., it is a great idea to apply the resursive here.

# An impletation of function until
def until(n, filter_func, v):
    # End subject, until the bound
    if v == n:
        return []
    # If v can satisfy the selection function, then return v and check next
    if filter_func(v):
        return [v]  + until (n, filter_func, v+1)
    # If v cannot satisfy the selection function, then check next
    else:
        return until(n, filter_func, v+1)

In functional programming, it is all based on the lambda calc in math, a new keyword lambda is used to expand the area of original python.

# This usage seems like to check whether the x is belongs to a set
mult_3_5 = lambda x: x%3 == 0 or x%5 == 0
print (mult_3_5(2), mult_3_5(3))
False True
# Combine the new lambda calc with the until() function, the result is just like find the join set of the set 'lambda' and the original full set
until(11, mult_3_5, 0)
[0, 3, 5, 6, 9, 10]

Python also supports the hybrid solution to include FP into procedural programming:

print([x for x in range(0,11) if x % 3 == 0 or x %5 == 0])
[0, 3, 5, 6, 9, 10]

The last form uses Nested Generated Expressions to iterate through the collection of the vars and select the taret ones

# In python the simple orderized sum seems won't be avoided by order
import timeit
print(timeit.timeit("((([]+[1])+[2])+[3])+[4]"), timeit.timeit("[]+([1]+([2]+([3]+[4])))"))
0.3882635319896508 0.39000111201312393

Using FP flavour python to calc sqrt()

Use FP method it is very easy to generate math results

# Newton method to approach sqrt(2)
# It is also a mathematical method, convert f(x) into the lambda calc result based on x
n = 2;
def next_(n, x):
    return (x+n/x)/2
f = lambda x: next_(n, x)

a = 1.0
[round(x ,4) for x in [a, f(a), f(f(a)), f(f(f(a)))]]
[1.0, 1.5, 1.4167, 1.4142]
# A simple repeat for function f with init var a
def repeat(f, a):
    yield a
    for v in repeat(f, f(a)):
        yield v

Python is not a pure FP lanuage and the current computer arches are not LISP machines, python uses recursive method to represent the yielding of the infinite list, then we must select a iterator as the generator of the values:

# General form
# for y in some_iter: yield y;
def within(eps, iterable):
    # Check whether is satisfy the end subject or just try to iter into next
    def head_tail(eps, a, iterable):
        b = next(iterable)
        if abs(a-b) <= eps:
            return b
        return head_tail(eps, b, iterable)
    return head_tail(eps, next(iterable), iterable)
# Full sqrt function in FP:
def sqrt(a, eps, n):
    return within(eps, repeat(lambda x: next_(n, x), a))

tgt=sqrt(1.0, 0.000001, 2)
print(tgt)
1.414213562373095

Summary

This FP flavour calc of sqrt() consists of following steps:

  • Define the function model to use and the iterator function
  • Define the end subject of the iteration
  • Iter and check the result: whether ||f(iter)-f(next_iter)|| meets the end subject
# Framework of this method:
# divide-calc-merge

#-divide
def next_(n, x):
    return (x+n/x)/2
f = lambda x: next_(n, x)

#-calc(multi times, generate f_n(a))
def repeat(f, a):
    yield a
    for v in repeat(f, f(a)):
        yield v

#-merge
def within(eps, iterable):
    # Check whether is satisfy the end subject or just try to iter into next
    def head_tail(eps, a, iterable):
        b = next(iterable)
        if abs(a-b) <= eps:
            return b
        return head_tail(eps, b, iterable)
    return head_tail(eps, next(iterable), iterable)

#-main
def sqrt(a, eps, n):
    return within(eps, repeat(lambda x: next_(n, x), a))

tgt=sqrt(1.0, 0.000001, 2)
print(tgt)
1.414213562373095
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末蜓斧,一起剝皮案震驚了整個(gè)濱河市祟敛,隨后出現(xiàn)的幾起案子昭伸,更是在濱河造成了極大的恐慌表制,老刑警劉巖嚷狞,帶你破解...
    沈念sama閱讀 211,639評(píng)論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)牧嫉,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,277評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人酣藻,你說我怎么就攤上這事曹洽。” “怎么了辽剧?”我有些...
    開封第一講書人閱讀 157,221評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵送淆,是天一觀的道長。 經(jīng)常有香客問我怕轿,道長偷崩,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,474評(píng)論 1 283
  • 正文 為了忘掉前任撤卢,我火速辦了婚禮环凿,結(jié)果婚禮上梧兼,老公的妹妹穿的比我還像新娘放吩。我一直安慰自己,他們只是感情好羽杰,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,570評(píng)論 6 386
  • 文/花漫 我一把揭開白布渡紫。 她就那樣靜靜地躺著,像睡著了一般考赛。 火紅的嫁衣襯著肌膚如雪惕澎。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,816評(píng)論 1 290
  • 那天颜骤,我揣著相機(jī)與錄音唧喉,去河邊找鬼。 笑死忍抽,一個(gè)胖子當(dāng)著我的面吹牛八孝,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播鸠项,決...
    沈念sama閱讀 38,957評(píng)論 3 408
  • 文/蒼蘭香墨 我猛地睜開眼干跛,長吁一口氣:“原來是場噩夢(mèng)啊……” “哼!你這毒婦竟也來了祟绊?” 一聲冷哼從身側(cè)響起楼入,我...
    開封第一講書人閱讀 37,718評(píng)論 0 266
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎牧抽,沒想到半個(gè)月后嘉熊,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,176評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡扬舒,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,511評(píng)論 2 327
  • 正文 我和宋清朗相戀三年阐肤,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片呼巴。...
    茶點(diǎn)故事閱讀 38,646評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡泽腮,死狀恐怖御蒲,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情诊赊,我是刑警寧澤厚满,帶...
    沈念sama閱讀 34,322評(píng)論 4 330
  • 正文 年R本政府宣布,位于F島的核電站碧磅,受9級(jí)特大地震影響碘箍,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜鲸郊,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,934評(píng)論 3 313
  • 文/蒙蒙 一丰榴、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧秆撮,春花似錦四濒、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,755評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至舒裤,卻和暖如春喳资,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背腾供。 一陣腳步聲響...
    開封第一講書人閱讀 31,987評(píng)論 1 266
  • 我被黑心中介騙來泰國打工仆邓, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人伴鳖。 一個(gè)月前我還...
    沈念sama閱讀 46,358評(píng)論 2 360
  • 正文 我出身青樓节值,卻偏偏與公主長得像,于是被迫代替她去往敵國和親黎侈。 傳聞我的和親對(duì)象是個(gè)殘疾皇子察署,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,514評(píng)論 2 348

推薦閱讀更多精彩內(nèi)容