Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Functional Programming

runninghack
November 05, 2012

Functional Programming

runninghack

November 05, 2012
Tweet

More Decks by runninghack

Other Decks in Programming

Transcript

  1. • Python -> Ruby 简单 • Java -> C# 简单

    • 第一次学FPL 见鬼了!
  2. 代表语言 • Lisp(强动态类型) – Common Lisp – Scheme • Haskell(纯函数式语言)

    • F#(强静态类型) • ML(强静态类型) • Erlang(强动态类型)
  3. λ演算的语法 使用BNF范式定义: • <expression>::=<name>|<function>|<application> • //函数抽象:用来生成函数 • < function >::=λ

    < name >.< expression > • 例: λ x. x+3 • //函数作用:使函数作用于参数 • < application >::=(< expression > < expression >) • 例: λ x. x+3 4 =>7
  4. λ演算的公理 α-置换公理: • λ x y. x+y == λ a

    b. a+b β-归约公理: • (λ x y. x+y) a b => a+b
  5. 前置知识 - Currying • Func<int, Func<int, int>> f = x

    => y => x + y; • int i = f(1)(2); • f 等于这样一个函数,接受一个int参数x, 并返回另一个函数Func<int, int>,这个函 数再接收一个int参数y,且对这个函数的调 用结果是x + y
  6. 题外话 – 丘奇数 • 零是 lambda s z . z

    • 一是 lambda s z . s z • 二是 lambda s z . s (s z) • …… • lambda s z . s sn z • add = lambda s z x y . x s (y s z)
  7. 实现递归 计算n的阶乘: • f (x) = λ x. x <

    1 ? 1 : x * f(x - 1) 但是在lambda演算中,f= 只是一个语法糖, 在表达式完成之前没有意义 Lambda演算不直接支持递归,我们需要实现 它
  8. • f (x)= λx. x < 1 ? 1 :

    x * f(x - 1) • 无法调用自身,那么就给自身当做参数↓ • 设F(f)(x) = λf λx. x < 1 ? 1 : x * f(x - 1) • 进行currying,F(f)=f,但是F的第一个参数 是什么呢?
  9. 试试对不对 • Y g = (λf.(λx . f (x x))

    (λx . f (x x))) g • Y g = (λx. g (x x)) (λx . g (x x)) • Y g = (λy. g (y y)) (λx . g (x x)) • Y g = g ((λx. g (x x)) (λx . g (x x))) • Y g = g (Y g) 即 Y g = g (Y g)
  10. 试着用一下Y组合子 g = λ f n. n==0 1 n *

    f(n-1) 则递归函数为g(Y(g)) g(Y(g)) 4 = 4==0 1 4 * Y(g) 3 = 4 * Y(g) 3 = 4 * g(Y(g)) 3 //正是递归!
  11. 数据结构 - pair • (define p (cons 4 5)) •

    =>(4, 5) • 操作: car cdr set-car! set-cdr!
  12. 数据结构 - list • (define la (list 1 2 3

    4 5)) • 操作:length, list-ref, list-set! • (make-list 5 6)=>(6 6 6 6 6)
  13. 函数 • ((lambda (x) (+ x x)) 5) =>10 •

    (define add5 (lambda (x) (+ x 5)))
  14. if 结构 • (if 测试 过程1 过程2) • (if (=

    x 0) (display ―is zero‖)(display ―not zero‖))
  15. cond 结构 • (cond ((测试)操作) … (else 操作)) • (define

    w (lambda (x) (cond ((< x 0) 'lower) ((> x 0) 'upper) (else 'equal))))
  16. case 结构 • (case (表达式) ((值) 操作)) ... (else 操作)))

    • (case (* 2 3) ((2 3 5 7) 'prime) ((1 4 6 8 9) 'composite))
  17. factorial另一种实现 • (define (factorial) (define (iter product counter) //块结构 (if

    (> counter n) product (iter (* counter product) (+ counter 1)))) (iter 1 1))
  18. 递归过程 vs 递归计算过程 • 递归过程是语法形 式上的事实 • factorial的第二种 实现在语法上是递 归的

    • 递归计算过程是计 算过程的进展方式 • factorial的第二种 实现在计算过程上 时迭代的