Functional Programming 之二三事

Preview:

DESCRIPTION

2009 Taiwan Yahoo! Intern share by Leeheng.

Citation preview

Functional

LeehengJuly 31, 2009

的二三事Programming

2009年7月31日星期五

Functional

LeehengJuly 31, 2009

的二三事ProgrammingBeta

2009年7月31日星期五

Agenda

2

About MyselfWhy This Topic

Programming ParadigmPL Moving On

Why FP MattersIP VS DP

Function, Lambda CalculusHigh Order Function, Currying

No Side Effect, Referential TransparentLeast Surprise, No UpdateRecursion, Lazy Evaluation

Pattern Matching, Tail recursionMemoization, Closure

Loop Helper

ExampleStory

ReferenceQuestion

開場 10min

過場 25min

下場 25min

2009年7月31日星期五

Agenda

2

About MyselfWhy This Topic

Programming ParadigmPL Moving On

Why FP MattersIP VS DP

Function, Lambda CalculusHigh Order Function, Currying

No Side Effect, Referential TransparentLeast Surprise, No UpdateRecursion, Lazy Evaluation

Pattern Matching, Tail recursionMemoization, Closure

Loop Helper

ExampleStory

ReferenceQuestion

開場 10min

過場 25min

下場 25min

2009年7月31日星期五

Agenda

2

About MyselfWhy This Topic

Programming ParadigmPL Moving On

Why FP MattersIP VS DP

Function, Lambda CalculusHigh Order Function, Currying

No Side Effect, Referential TransparentLeast Surprise, No UpdateRecursion, Lazy Evaluation

Pattern Matching, Tail recursionMemoization, Closure

Loop Helper

ExampleStory

ReferenceQuestion

開場 10min

過場 25min

下場 25min

2009年7月31日星期五

Agenda

2

About MyselfWhy This Topic

Programming ParadigmPL Moving On

Why FP MattersIP VS DP

Function, Lambda CalculusHigh Order Function, Currying

No Side Effect, Referential TransparentLeast Surprise, No UpdateRecursion, Lazy Evaluation

Pattern Matching, Tail recursionMemoization, Closure

Loop Helper

ExampleStory

ReferenceQuestion

開場 10min

過場 25min

下場 25min

2009年7月31日星期五

ABOUT MYSELF

3

Y! 2009 Search Team InternLeeheng Ma

NCCU MIS undergraduateInterests : Algorithm, Programming language, Compiler,

Web Technology.

2009年7月31日星期五

WHY THIS TOPIC

4

2009年7月31日星期五

WHY THIS TOPIC

4

因為我沒有研究可報....

2009年7月31日星期五

WHY THIS TOPIC

4

因為我沒有研究可報....

因為 Programming Language 是最貼近我們 RD 的東西

2009年7月31日星期五

Programming Paradigm

5

Programming paradigm is a Fundamental style of computer programming.

2009年7月31日星期五

Programming Paradigm

5

Programming paradigm is a Fundamental style of computer programming.

For solving Software Engineering Problems.

2009年7月31日星期五

Programming Paradigm

5

Programming paradigm is a Fundamental style of computer programming.

For solving Software Engineering Problems.

編程典範 正在Programming Paradigm SHIFT

2009年7月31日星期五

Think Different

6

• A language that doesn't affect the way you think about programming, is not worth knowing.

--Alan Perlis

2009年7月31日星期五

Think Different

6

• A language that doesn't affect the way you think about programming, is not worth knowing.

--Alan Perlis

2009年7月31日星期五

Think Different

6

• A language that doesn't affect the way you think about programming, is not worth knowing.

--Alan Perlis

這是圖靈獎獎杯

2009年7月31日星期五

HOW MANY YOU KNOW ?

• Concurrent• Imperative• Declarative• Functional• Procedural• Prototype-based• Event-driven• Aspect-Oriented• Object-Oriented• Meta-Programming• Generic

7

Programming

2009年7月31日星期五

HOW MANY YOU KNOW ?

7

其實還有很多... Orz但.....就不管了...

2009年7月31日星期五

WHERE PL MOVING ON ?

8

2009年7月31日星期五

WHERE PL MOVING ON ?

8

2009年7月31日星期五

WHERE PL MOVING ON ?

8

2009年7月31日星期五

WHERE PL MOVING ON ?

8

2009年7月31日星期五

WHERE PL MOVING ON ?

8

2009年7月31日星期五

WHERE PL MOVING ON ?

8

2009年7月31日星期五

WHERE PL MOVING ON ?

8

2009年7月31日星期五

WHERE PL MOVING ON ?

8

2009年7月31日星期五

WHERE PL MOVING ON ?

8

2009年7月31日星期五

WHERE PL MOVING ON ?

8

2009年7月31日星期五

WHERE PL MOVING ON ?

8

2009年7月31日星期五

WHERE PL MOVING ON ?

8

2009年7月31日星期五

WHERE PL MOVING ON ?

8

2009年7月31日星期五

WHERE PL MOVING ON ?

8

2009年7月31日星期五

WHY FP MATTERS

9

名家背書

抽象思考

2009年7月31日星期五

WHY FP MATTERS

• Python, Ruby, Perl all use ideas form FP• Y!牌’s Hadoop and G牌‘s MapReduce are large

scale FP

9

名家背書

抽象思考

2009年7月31日星期五

WHY FP MATTERS

• Python, Ruby, Perl all use ideas form FP• Y!牌’s Hadoop and G牌‘s MapReduce are large

scale FP

9

名家背書

抽象思考

ModularityInterchangeable partsEasy test and debugEasy optimizationFunction as dataPattern MatchingConcurrent ProcessingClosureLazy EvaluationReferential transparency

• No Side Effect• High Order Function

2009年7月31日星期五

IP VS FP

•Imperative Programming– Computation:Executing statements to change state.– Program:Consists of a sequence of commands.

•Functional Programming– Computation:Evaluation of expressions.– Expression:Formed by using functions to combine

basic values.

10

The focus is on what, not how

2009年7月31日星期五

IP VS FP

•Imperative Programming– Computation:Executing statements to change state.– Program:Consists of a sequence of commands.

•Functional Programming– Computation:Evaluation of expressions.– Expression:Formed by using functions to combine

basic values.

10

The focus is on what, not how

C++ JavaOOP

2009年7月31日星期五

IP VS FP

•Imperative Programming– Computation:Executing statements to change state.– Program:Consists of a sequence of commands.

•Functional Programming– Computation:Evaluation of expressions.– Expression:Formed by using functions to combine

basic values.

10

The focus is on what, not how

C++ JavaOOP

Lisp HaskellErlang

2009年7月31日星期五

Create Sandwich

11

Imperative

Functional

2009年7月31日星期五

Create Sandwich

11

1. Take a bread2. Spread bread with butter3. Put cheese on the bread4. return sandwich

Imperative

Functional

2009年7月31日星期五

Create Sandwich

11

1. Take a bread2. Spread bread with butter3. Put cheese on the bread4. return sandwich

Imperative

return put ( cheese, spread(butter, bread) )

Functional

2009年7月31日星期五

12

Features

2009年7月31日星期五

Function is ?

12

In computer science, a subroutine or subprogram (also called procedure, method, function, or routine) is a portion of code within a larger program, which performs a specific task and is relatively independent of the remaining code.

2009年7月31日星期五

Function is ?

12

The mathematical concept of a function expresses the intuitive idea that one quantity (the argument of the function, also known as the input) completely determines another quantity (the value, or output).

2009年7月31日星期五

Function is ?

12

The mathematical concept of a function expresses the intuitive idea that one quantity (the argument of the function, also known as the input) completely determines another quantity (the value, or output).

2009年7月31日星期五

Function is ?

12

The mathematical concept of a function expresses the intuitive idea that one quantity (the argument of the function, also known as the input) completely determines another quantity (the value, or output).

So we minimize function!!

2009年7月31日星期五

Lambda Calculus

13

The λ-calculus was developed by the logician Alonzo Church in 1930’s as a tool to study functions and computability.

2009年7月31日星期五

λ Calculus

14

Equivalent to Turing MachinesTuring 1937

Equivalent to recursive functionsKleene 1936

(λ x. x + 2)

2009年7月31日星期五

λ Calculus

14

Equivalent to Turing MachinesTuring 1937

Equivalent to recursive functionsKleene 1936

(λ x. x + 2) = (x) { return x + 2}

2009年7月31日星期五

λ Calculus

14

Equivalent to Turing MachinesTuring 1937

Equivalent to recursive functionsKleene 1936

(λ x. x + 2)

(λ x. x + 2) 3 = 5

= (x) { return x + 2}

2009年7月31日星期五

λ Calculus

14

Equivalent to Turing MachinesTuring 1937

Equivalent to recursive functionsKleene 1936

(λ f. f 3)(λ x. x+2) = ?

2009年7月31日星期五

λ Calculus

14

Equivalent to Turing MachinesTuring 1937

Equivalent to recursive functionsKleene 1936

(λ f. f 3)(λ x. x+2) = ?

= (λ x. x + 2) 3= 3 + 2

2009年7月31日星期五

High Order Function

15

• Functions take other functions as parameters

• Functions return functions as results

2009年7月31日星期五

High Order Function

15

• Functions take other functions as parameters

• Functions return functions as results

∑ f(x) x∈L

2009年7月31日星期五

High Order Function

15

• Functions take other functions as parameters

• Functions return functions as results d f(x)

dx = f’(x)

∑ f(x) x∈L

2009年7月31日星期五

Mathematics

16

2009年7月31日星期五

Mathematics

16

OK, no more mathematics.

2009年7月31日星期五

Design Pattern

17

2009年7月31日星期五

Design Pattern

17

Adapter Pattern

2009年7月31日星期五

Design Pattern

17

Adapter Pattern

2009年7月31日星期五

Design Pattern

17

Adapter Pattern

+

2009年7月31日星期五

Design Pattern

17

Adapter Pattern

2009年7月31日星期五

Design Pattern

17

Adapter Pattern

2009年7月31日星期五

Currying

18

把接受多個參數的函數變換成接受一個單一參數(最初函數的第一個參數)的函數,並且返回接受餘下的參數而且返回結果的新函數的技術。

AJAX 的 callback function

2009年7月31日星期五

No Side Effect

19

Output is solely dependent of input.

input outputPure Function

2009年7月31日星期五

No Side Effect

19

Output is solely dependent of input.

input output

States

With Assignment

Impure Function

2009年7月31日星期五

No Side Effect

19

Output is solely dependent of input.

input output

States

With Assignment

Impure Function

Can replace f(x) + f(x) with 2*f(x)?

2009年7月31日星期五

Referential Transparent

20

If the function f is referential transparent.

2009年7月31日星期五

Referential Transparent

20

If the function f is referential transparent.

What is this?

2009年7月31日星期五

Referential Transparent

20

What is this?

If Function result depends only on the values of its parameters.

Definition:

2009年7月31日星期五

Referential Transparent

20

What is this?

If Function result depends only on the values of its parameters.

Definition:

This concept occurs in mathematics, but it is broken by imperative programming languages.

Murmur:

2009年7月31日星期五

Side Effect

21

Consider the following C/Java function f:

2009年7月31日星期五

Side Effect

21

Consider the following C/Java function f:

f change the state outside the function.

2009年7月31日星期五

Principle Of Least Surprise

22

All possible inputs are listed in the parameter list, noworries about global state.Single assignment means that you never have to find where a variable updated, cause it is only defined one place in the entire function.Small function, easy to testing.(suit with TDD)

2009年7月31日星期五

No Update On Variables

23

Variables are similar to Variables in mathematics, they hold a value but they can’t be updated.

Definition:

Pure

Variables only assigned once.

2009年7月31日星期五

No Update On Variables

23

Variables are similar to Variables in mathematics, they hold a value but they can’t be updated.

Definition:

Pure

Variables only assigned once.

2009年7月31日星期五

No Update On Variables

23

Variables are similar to Variables in mathematics, they hold a value but they can’t be updated.

Definition:

Pure

So...We don’t need to care call by value, call by reference...etc.

Variables only assigned once.

2009年7月31日星期五

No Update On Variables

23

Variables are similar to Variables in mathematics, they hold a value but they can’t be updated.

Definition:

Pure

So...We don’t need to care call by value, call by reference...etc.

Variables only assigned once.

2009年7月31日星期五

Recursion Basics

24

How to Loop?Functional programs are usually H .

(with map, fold, filter)

Pure

2009年7月31日星期五

Recursion Basics

24

How to Loop?Functional programs are usually H .

(with map, fold, filter)eavily Recursive

Pure

2009年7月31日星期五

Recursion Basics

24

How to Loop?Functional programs are usually H .

(with map, fold, filter)eavily Recursive

Iteration.isEqualTo( Recursive); Pure

2009年7月31日星期五

Efficiency

25

It is true...Early:

Tail Recursion.Lazy Evaluation.MemoizationCommon Subexpression EliminationParallel Computing

Now:

2009年7月31日星期五

Efficiency

25

It is true...Early:

Tail Recursion.Lazy Evaluation.MemoizationCommon Subexpression EliminationParallel Computing

Now:

2009年7月31日星期五

Efficiency

25

It is true...Early:

Tail Recursion.Lazy Evaluation.MemoizationCommon Subexpression EliminationParallel Computing

Now:!=

2009年7月31日星期五

Efficiency

25

It is true...Early:

Tail Recursion.Lazy Evaluation.MemoizationCommon Subexpression EliminationParallel Computing

Now:

2009年7月31日星期五

Efficiency

25

It is true...Early:

Tail Recursion.Lazy Evaluation.MemoizationCommon Subexpression EliminationParallel Computing

Now:

2009年7月31日星期五

Chat in Pugs Project

26

From freenode, #perl6, 2005/3/2 http://xrl.us/e98m

19:08 < malaire> Does pugs yet have system() or backticks or qx// or any way to use system commands?19:08 < autrijus> malaire: no, but I can do one for you now. a sec19:09 < malaire> ok, I'm still reading YAHT, so I won't try to patch pugs just yet...19:09 < autrijus> you want unary system or list system?19:09 < autrijus> system("ls -l") vs system("ls", "-l")19:10 < malaire> perhaps list, but either is ok19:11 < autrijus> \\n Bool pre system (Str)\19:11 < autrijus> \\n Bool pre system (Str: List)\19:11 < autrijus> I'll do both :)19:11 < autrijus> done. testing.19:14 < autrijus> test passed. r386. enjoy19:14 < malaire> that's quite fast development :)19:14 < autrijus> :)

2009年7月31日星期五

Lazy Evaluation

27

lazy evaluation is the technique of delaying a computation until the result is required.Benefits:S1 = EXPR 1();S2 = EXPR 2();S2 = Concatenate(S1, S2);

Pure

2009年7月31日星期五

Lazy Evaluation

27

lazy evaluation is the technique of delaying a computation until the result is required.Benefits:S1 = EXPR 1();S2 = EXPR 2();S2 = Concatenate(S1, S2);

Pure

2009年7月31日星期五

Lazy Evaluation

27

lazy evaluation is the technique of delaying a computation until the result is required.Benefits:S1 = EXPR 1();S2 = EXPR 2();S2 = Concatenate(S1, S2);

In Haskell, we don’t run S1 and S2 before we call Concatenate, we even don’t know which one evaluate first!

Pure

2009年7月31日星期五

Lazy Evaluation

27

lazy evaluation is the technique of delaying a computation until the result is required.Benefits:S1 = EXPR 1();S2 = EXPR 2();S2 = Concatenate(S1, S2);

In Haskell, we don’t run S1 and S2 before we call Concatenate, we even don’t know which one evaluate first!

Pure

Benefits:

2009年7月31日星期五

Pattern Matching

28

A Good Picture Can Tell Every Thing!

2009年7月31日星期五

Tail Recursion

29

2009年7月31日星期五

Tail Recursion

29

fac 55 * (fac 4) 5 * 4 * (fac 3)5 * 4 * 3 * (fac 2) 5 * 4 * 3 * 2 * (fac 1) 5 * 4 * 3 * 2 * 1 * (fac 0) 5 * 4 * 3 * 2 * 1 * 1..120

Stack

Time

2009年7月31日星期五

Tail Recursion

29

2009年7月31日星期五

Tail Recursion

29

fac 5tailfac 5 1tailfac 4 5 * 1tailfac 3 4 * 5 * 1tailfac 2 3 * 4 * 5 * 1tailfac 1 2 * 3 * 4 * 5 * 1tailfac 0 1 * 2 * 3 * 4 * 5 * 1..120

Stack

Time

2009年7月31日星期五

Tail Recursion

29

fac 5tailfac 5 1tailfac 4 5 * 1tailfac 3 4 * 5 * 1tailfac 2 3 * 4 * 5 * 1tailfac 1 2 * 3 * 4 * 5 * 1tailfac 0 1 * 2 * 3 * 4 * 5 * 1..120

Stack

Time

5 14 53 202 601 1200 120

2009年7月31日星期五

Tail Recursion

29

fac 5tailfac 5 1tailfac 4 5 * 1tailfac 3 4 * 5 * 1tailfac 2 3 * 4 * 5 * 1tailfac 1 2 * 3 * 4 * 5 * 1tailfac 0 1 * 2 * 3 * 4 * 5 * 1..120

Stack

Time

5 14 53 202 601 1200 120

Tail Recursion can be optimize to loop!!

2009年7月31日星期五

Memoization

30

Definition:Memoization is an optimization technique used primarily to speed up computer programs by having function calls avoid repeating the calculation of results for previously-processed inputs.

2009年7月31日星期五

Memoization

30

Definition:Memoization is an optimization technique used primarily to speed up computer programs by having function calls avoid repeating the calculation of results for previously-processed inputs.

2009年7月31日星期五

Closure

31

In C

2009年7月31日星期五

Closure

31

In C

New or Malloc.

2009年7月31日星期五

Closure

31

In C

But Global is

2009年7月31日星期五

Closure

31

In C

static and dynamic.Another issue: scope

2009年7月31日星期五

Closure

31

In C

static and dynamic.Another issue: scope

I AmSymbol Table

GlobalI Am

Symbol Table

2009年7月31日星期五

Closure

31

In C

static and dynamic.Another issue: scope

I AmSymbol Table

GlobalI Am

Symbol Table

Local

2009年7月31日星期五

Closure

31

In C

static and dynamic.Another issue: scope

I AmSymbol Table

Global

2009年7月31日星期五

Closure

31

In C

static and dynamic.Another issue: scope

2009年7月31日星期五

Closure

31

In C

static and dynamic.Another issue: scope

2009年7月31日星期五

Closure

31

In C

static and dynamic.Another issue: scope

2009年7月31日星期五

Loop Helper

32

Not only Recursion, but also Loop Helper?

Recursion : divided and conquer

Loop : don’t do that so complicate

2009年7月31日星期五

Folding

33

Alias : reduce

2009年7月31日星期五

Folding

33

Alias : reduce

OperatorInitial valueList

2009年7月31日星期五

Folding

33

Alias : reduce

2009年7月31日星期五

Folding

33

Alias : reduce

2009年7月31日星期五

Folding

33

Alias : reduce

2009年7月31日星期五

Mapping

34

2009年7月31日星期五

Mapping

34

2009年7月31日星期五

Mapping

34

2009年7月31日星期五

Mapping

34

Function f()a, b, c, ..., z f(a), f(b), f(c), ..., f(z)

2009年7月31日星期五

Mapping

34

2009年7月31日星期五

Filtering

35

Definition:

Function f()a, b, c, ..., z a’, b’, c’, ..., z’

if (p?) w, then send w to output

2009年7月31日星期五

Filtering

35

Definition:

Function f()a, b, c, ..., z a’, b’, c’, ..., z’

if (p?) w, then send w to output

2009年7月31日星期五

Quick Sort

36

2009年7月31日星期五

Quick Sort

36

2009年7月31日星期五

Quick Sort

36

2009年7月31日星期五

Quick Sort

36

2009年7月31日星期五

Insert Sort

37

2009年7月31日星期五

Insert Sort

37

2009年7月31日星期五

Insert Sort

37

2009年7月31日星期五

Insert Sort

37

2009年7月31日星期五

Insert Sort

37

2009年7月31日星期五

Story

38

Paul GrahamDevelop Y! Store by Lisp.唐鳳Develop Perl6 by Haskell.蔡學鏞“學會 Lisp 會讓你生產力大增” by Beyond JavaMIT CS6.001 Structure and Interpretation of Computer Programs

2009年7月31日星期五

Reference

• Blog– 以 C 語言實做 Functional Language 的 Currying– JavaScript Memoization– Functional Programming For The Rest of Us– Functional Programming in JavaScript and Ruby

• Book– Practical Common Lisp– Haskell: The Craft of Functional Programming– The Haskell School of Expression: Learning Functional

Programming through Multimedia• Web

– Wikipedia– Understanding Haskell Monads

39

2009年7月31日星期五

Reference

• Web– DJWS的網路日誌– Why Functional Programming Matters• Slide– Introduction To Functional Programming– Functional Programming With Python (EuroPython 2008)– Functional Programming In Java– Understanding Functional Programming– Functional Programming– Functional Concepts for OOP Developers– Special thanks the slides form NCCU CS Chen Kung professor

40

2009年7月31日星期五

41

Question ?

2009年7月31日星期五

Recommended