SlideShare a Scribd company logo
Functional
  Programming
       Leeheng
       July 31, 2009
Functional  Bet
  Programming   a


          Leeheng
          July 31, 2009
Agenda
                    About Myself
                   Why This Topic
               Programming Paradigm
10min              PL Moving On
                  Why FP Matters
                      IP VS DP

             Function, Lambda Calculus
            High Order Function, Currying
        No Side Effect, Referential Transparent
              Least Surprise, No Update
25min        Recursion, Lazy Evaluation
           Pattern Matching, Tail recursion
                Memoization, Closure
                     Loop Helper

                       Example
                        Story
25min                 Reference
                      Question
                                                  2
Agenda
                    About Myself
                   Why This Topic
               Programming Paradigm
10min              PL Moving On
                  Why FP Matters
                      IP VS DP

             Function, Lambda Calculus
            High Order Function, Currying
        No Side Effect, Referential Transparent
              Least Surprise, No Update
25min        Recursion, Lazy Evaluation
           Pattern Matching, Tail recursion
                Memoization, Closure
                     Loop Helper

                       Example
                        Story
25min                 Reference
                      Question
                                                  2
Agenda
                    About Myself
                   Why This Topic
               Programming Paradigm
10min              PL Moving On
                  Why FP Matters
                      IP VS DP

             Function, Lambda Calculus
            High Order Function, Currying
        No Side Effect, Referential Transparent
              Least Surprise, No Update
25min        Recursion, Lazy Evaluation
           Pattern Matching, Tail recursion
                Memoization, Closure
                     Loop Helper

                       Example
                        Story
25min                 Reference
                      Question
                                                  2
Agenda
                    About Myself
                   Why This Topic
               Programming Paradigm
10min              PL Moving On
                  Why FP Matters
                      IP VS DP

             Function, Lambda Calculus
            High Order Function, Currying
        No Side Effect, Referential Transparent
              Least Surprise, No Update
25min        Recursion, Lazy Evaluation
           Pattern Matching, Tail recursion
                Memoization, Closure
                     Loop Helper

                       Example
                        Story
25min                 Reference
                      Question
                                                  2
ABOUT MYSELF

Leeheng Ma
Y! 2009 Search Team Intern
NCCU MIS undergraduate
Interests : Algorithm,
            Programming language,
            Compiler,
            Web Technology.



                                    3
WHY THIS TOPIC




                 4
WHY THIS TOPIC


                 ....




                        4
WHY THIS TOPIC


                  ....

Programming Language
                 RD



                         4
Programming Paradigm

Programming paradigm is a
Fundamental style of computer programming.




                                      5
Programming Paradigm

Programming paradigm is a
Fundamental style of computer programming.
                   For solving Software Engineering Problems.




                                                       5
Programming Paradigm

Programming paradigm is a
Fundamental style of computer programming.
                   For solving Software Engineering Problems.




Programming Paradigm SHIFT
                                                       5
Think Different

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




                                          6
Think Different

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




                                          6
Think Different

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




                                          6
HOW MANY YOU KNOW ?

• Concurrent
• Imperative
• Declarative
• Functional
• Procedural
                     Programming
• Prototype-based
• Event-driven
• Aspect-Oriented
• Object-Oriented
• Meta-Programming
• Generic
                                   7
HOW MANY YOU KNOW ?




     ... Orz
        .....   ...
                      7
WHERE PL MOVING ON ?




                       8
WHERE PL MOVING ON ?




                       8
WHERE PL MOVING ON ?




                       8
WHERE PL MOVING ON ?




                       8
WHERE PL MOVING ON ?




                       8
WHERE PL MOVING ON ?




                       8
WHERE PL MOVING ON ?




                       8
WHERE PL MOVING ON ?




                       8
WHERE PL MOVING ON ?




                       8
WHERE PL MOVING ON ?




                       8
WHERE PL MOVING ON ?




                       8
WHERE PL MOVING ON ?




                       8
WHERE PL MOVING ON ?




                       8
WHERE PL MOVING ON ?




                       8
WHY FP MATTERS




                 9
WHY FP MATTERS


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




                                          9
WHY FP MATTERS


• Python,  Ruby, Perl all use ideas form FP
• Y! ’s Hadoop and  G ‘s MapReduce are large
  scale FP
                         Modularity
                         Interchangeable parts
                         Easy test and debug
                         Easy optimization
                         Function as data
 • No Side Effect        Pattern Matching
                         Concurrent Processing
 • High Order Function   Closure
                         Lazy Evaluation
                         Referential transparency


                                                    9
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.

   The focus is on what, not how



                                                 10
IP VS FP

                                                OO




                                   C+
                                                  P
• Imperative Programming                 Java




                                     +
 – 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.

   The focus is on what, not how



                                                      10
IP VS FP

                                                 OO




                                   C+
                                                      P
• Imperative Programming                  Java




                                     +
 – Computation Executing statements to change state.
 – Program Consists of a sequence of commands.
                                                        g
                                   Lisp   Ha      E rlan
• Functional Programming                    ske
                                                 ll
 – Computation Evaluation of expressions.
 – Expression Formed by using functions to combine
   basic values.

   The focus is on what, not how



                                                            10
Create Sandwich


Imperative




Functional




                      11
Create Sandwich


Imperative

  1.   Take a bread
  2.   Spread bread with butter
  3.   Put cheese on the bread
  4.   return sandwich


Functional




                                  11
Create Sandwich


Imperative

  1.   Take a bread
  2.   Spread bread with butter
  3.   Put cheese on the bread
  4.   return sandwich


Functional

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




                                            11
Features


           12
Function is ?

 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.




                                                            12
Function is ?

 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).




                                                           12
Function is ?

 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).




                                                           12
Function is ?

       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!!



                                                                 12
Lambda Calculus



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




                                      13
λ Calculus

Equivalent to Turing Machines
                                    Turing 1937
Equivalent to recursive functions
                                    Kleene 1936


(λ x. x + 2)




                                                  14
λ Calculus

Equivalent to Turing Machines
                                     Turing 1937
Equivalent to recursive functions
                                    Kleene 1936


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




                                                   14
λ Calculus

 Equivalent to Turing Machines
                                     Turing 1937
 Equivalent to recursive functions
                                     Kleene 1936


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

(λ x. x + 2) 3 = 5




                                                   14
λ Calculus

Equivalent to Turing Machines
                                    Turing 1937
Equivalent to recursive functions
                                    Kleene 1936


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




                                                  14
λ Calculus

Equivalent to Turing Machines
                                    Turing 1937
Equivalent to recursive functions
                                    Kleene 1936


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

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




                                                  14
High Order Function


• Functions take other functions
  as parameters

• Functions return functions as
  results




                                   15
High Order Function


• Functions take other functions
  as parameters                    ∑ f(x)
                                   x∈L


• Functions return functions as
  results




                                         15
High Order Function


• Functions take other functions
  as parameters                      ∑ f(x)
                                     x∈L


• Functions return functions as
  results                          d f(x)
                                     dx     = f’(x)




                                             15
Mathematics




              16
Mathematics

OK, no more mathematics.




                           16
Design Pattern




                 17
Design Pattern

Adapter Pattern




                       17
Design Pattern

Adapter Pattern




                       17
Design Pattern

Adapter Pattern




                  +


                       17
Design Pattern

Adapter Pattern




                       17
Design Pattern

Adapter Pattern




                       17
Currying

                           (   )




AJAX   callback function




                                   18
No Side Effect

Output is solely dependent of input.




  input                       output
             Pure Function




                                       19
No Side Effect

Output is solely dependent of input.
                States




  input                       output
            Impure Function




            With Assignment




                                       19
No Side Effect

   Output is solely dependent of input.
                   States




     input                       output
               Impure Function




               With Assignment


Can replace f(x) + f(x) with 2*f(x)?
                                          19
Referential Transparent




           If the function f is
           referential transparent.




                             20
Referential Transparent




           If the function f is
           referential transparent.


           What is this?


                             20
Referential Transparent

What is this?

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




                                    20
Referential Transparent

What is this?

 Definition:
 If Function result depends only
 on the values of its parameters.
 Murmur:
 This concept occurs in mathematics, but
 it is broken by imperative programming
 languages.

                                    20
Side Effect

Consider the following C/Java function f:




                                            21
Side Effect

Consider the following C/Java function f:




                                     f change the state
                                    outside the function.




                                                 21
Principle Of Least Surprise

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)

                                       22
No Update On Variables

Definition:
Variables are similar to Variables in
mathematics, they hold a value but
they can’t be updated.
  Variables only assigned once.


                                             Pure




                                        23
No Update On Variables

Definition:
Variables are similar to Variables in
mathematics, they hold a value but
they can’t be updated.
  Variables only assigned once.


                                             Pure




                                        23
No Update On Variables

Definition:
Variables are similar to Variables in
mathematics, they hold a value but
they can’t be updated.
  Variables only assigned once.
So...We don’t need to care call by
value, call by reference...etc.
                                             Pure




                                        23
No Update On Variables

Definition:
Variables are similar to Variables in
mathematics, they hold a value but
they can’t be updated.
  Variables only assigned once.
So...We don’t need to care call by
value, call by reference...etc.
                                             Pure




                                        23
Recursion Basics

How to Loop?
Functional programs
are usually
H                 .
   (with map, fold, filter)



                                   Pure


                              24
Recursion Basics

How to Loop?
Functional programs
are usually
Heavily Recursive.
   (with map, fold, filter)



                                   Pure


                              24
Recursion Basics

How to Loop?
Functional programs
are usually
Heavily Recursive.
   (with map, fold, filter)



Iteration.isEqualTo( Recursive);        Pure


                                   24
Efficiency

Early:
  It is true...
Now:
  Tail Recursion.
  Lazy Evaluation.
  Memoization
  Common Subexpression Elimination
  Parallel Computing

                               25
Efficiency

Early:
  It is true...
Now:
  Tail Recursion.
  Lazy Evaluation.
  Memoization
  Common Subexpression Elimination
  Parallel Computing

                               25
Efficiency

Early:
  It is true...
Now:
  Tail Recursion. !=
  Lazy Evaluation.
  Memoization
  Common Subexpression Elimination
  Parallel Computing

                               25
Efficiency

Early:
  It is true...
Now:
  Tail Recursion.
  Lazy Evaluation.
  Memoization
  Common Subexpression Elimination
  Parallel Computing

                               25
Efficiency

Early:
  It is true...
Now:
  Tail Recursion.
  Lazy Evaluation.
  Memoization
  Common Subexpression Elimination
  Parallel Computing

                               25
Chat in Pugs Project

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 sec
19: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 ok
19: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. enjoy
19:14 < malaire> that's quite fast development :)
19:14 < autrijus> :)



                                                                               26
Lazy Evaluation

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


                                       27
Lazy Evaluation

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


                                       27
Lazy Evaluation

lazy evaluation is the technique of delaying
a computation until the result is required.
Benefits:
                            In Haskell, we don’t run
S1 = EXPR 1();              S1 and S2 before we
                            call Concatenate, we
S2 = EXPR 2();              even don’t know which
S2 = Concatenate(S1, S2);   one evaluate first!




                                                       Pure


                                               27
Lazy Evaluation

lazy evaluation is the technique of delaying
a computation until the result is required.
Benefits:
                            In Haskell, we don’t run
S1 = EXPR 1();              S1 and S2 before we
                            call Concatenate, we
S2 = EXPR 2();              even don’t know which
S2 = Concatenate(S1, S2);   one evaluate first!



Benefits:
                                                       Pure


                                               27
Pattern Matching

A Good Picture Can Tell Every Thing!




                                  28
Tail Recursion




                 29
Tail Recursion
                                         Stack

         fac   5
         5 *   (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
Time

                                            29
Tail Recursion




                 29
Tail Recursion
                                                Stack

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

                                                   29
Tail Recursion
                                              Stack

         fac 5
         tailfac   5   1
         tailfac   4   5 *   1
         tailfac   3   4 *
                       20    5   *   1
         tailfac   2   3 *
                       60    4   *   5 * 1
         tailfac   1   2 *
                       120   3   *   4 * 5 * 1
         tailfac   0   1 *
                       120   2   *   3 * 4 * 5 * 1
         .
         .
         120
Time

                                                 29
Tail Recursion
                                              Stack

         fac 5
         tailfac   5   1
         tailfac   4   5 *   1
         tailfac   3   4 *
                       20    5   *   1
         tailfac   2   3 *
                       60    4   *   5 * 1
         tailfac   1   2 *
                       120   3   *   4 * 5 * 1
         tailfac   0   1 *
                       120   2   *   3 * 4 * 5 * 1
         .
         .             Tail Recursion can be
Time
         120           optimize to loop!!
                                                 29
Memoization

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.



                                 30
Memoization

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.



                                 30
Closure

In C




                 31
Closure

In C

                 New or Malloc.




                                  31
Closure

In C

                 But Global is




                                 31
Closure

In C

                 Another issue: scope
                 static and dynamic.




                               31
Closure

In C

                 Another issue: scope
                 static and dynamic.



  Global
     I Am
  Symbol Table



                               31
Closure

In C

                         Another issue: scope
                         static and dynamic.



  Global         Local
     I Am           I Am
  Symbol Table   Symbol Table



                                       31
Closure

In C

                 Another issue: scope
                 static and dynamic.



  Global
     I Am
  Symbol Table



                               31
Closure

In C

                 Another issue: scope
                 static and dynamic.




                               31
Closure

In C

                 Another issue: scope
                 static and dynamic.




                               31
Closure

In C

                 Another issue: scope
                 static and dynamic.




                               31
Loop Helper

Not only Recursion, but also Loop Helper?

Recursion :
divided and conquer

Loop :
don’t do that so
complicate


                                     32
Folding

Alias : reduce




                 33
Folding

Alias : reduce

                 Operator
                 Initial value
                 List




                                 33
Folding

Alias : reduce




                 33
Folding

Alias : reduce




                 33
Folding

Alias : reduce




                 33
Mapping




          34
Mapping




          34
Mapping




          34
Mapping




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




                                                          34
Mapping




          34
Filtering

Definition:




              if (p?) w, then send w to output
     a, b, c, ..., z                      a’, b’, c’, ..., z’
                         Function f()



                                                                35
Filtering

Definition:




              if (p?) w, then send w to output
     a, b, c, ..., z                      a’, b’, c’, ..., z’
                         Function f()



                                                                35
Quick Sort




             36
Quick Sort




             36
Quick Sort




             36
Quick Sort




             36
Insert Sort




              37
Insert Sort




              37
Insert Sort




              37
Insert Sort




              37
Insert Sort




              37
Story

Paul Graham
Develop Y! Store by Lisp.

Develop Perl6 by Haskell.

“     Lisp                  ” by Beyond Java
MIT CS
6.001 Structure and Interpretation of
Computer Programs
                                     38
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
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
Question ?


             41

More Related Content

Similar to Functional Programming 之二三事 (20)

PPT
Functional Programming - Past, Present and Future
Pushkar Kulkarni
 
PPT
Functional Programming Past Present Future
IndicThreads
 
PPTX
Functional programming
Prateek Jain
 
PDF
Functional Programming #FTW
Adriano Bonat
 
PPTX
Unraveling the mystery of monads
Faisal Waris
 
PDF
Dimitry Solovyov - The imminent threat of functional programming
Dmitry Buzdin
 
PDF
Introduction to functional programming (In Arabic)
Omar Abdelhafith
 
PDF
Introduction to functional programming
Konrad Szydlo
 
PDF
Introduction to functional programming
Thang Mai
 
PPTX
The joy of functional programming
Steve Zhang
 
PPTX
Functional Programming Fundamentals
Shahriar Hyder
 
PPTX
Good functional programming is good programming
kenbot
 
KEY
LISP: How I Learned To Stop Worrying And Love Parantheses
Dominic Graefen
 
PPT
Trends in Programming Technology you might want to keep an eye on af Bent Tho...
InfinIT - Innovationsnetværket for it
 
PPT
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16
Innovecs
 
PPT
Introductory func prog
Oleksandr Khomenko
 
PPTX
Why functional programming in C# & F#
Riccardo Terrell
 
PDF
Go Beyond Higher Order Functions: A Journey into Functional Programming
Lex Sheehan
 
PPTX
Functional Programming Fundamentals
OleksiyTereshchenko
 
PPT
Programming Paradigms
Janeve George
 
Functional Programming - Past, Present and Future
Pushkar Kulkarni
 
Functional Programming Past Present Future
IndicThreads
 
Functional programming
Prateek Jain
 
Functional Programming #FTW
Adriano Bonat
 
Unraveling the mystery of monads
Faisal Waris
 
Dimitry Solovyov - The imminent threat of functional programming
Dmitry Buzdin
 
Introduction to functional programming (In Arabic)
Omar Abdelhafith
 
Introduction to functional programming
Konrad Szydlo
 
Introduction to functional programming
Thang Mai
 
The joy of functional programming
Steve Zhang
 
Functional Programming Fundamentals
Shahriar Hyder
 
Good functional programming is good programming
kenbot
 
LISP: How I Learned To Stop Worrying And Love Parantheses
Dominic Graefen
 
Trends in Programming Technology you might want to keep an eye on af Bent Tho...
InfinIT - Innovationsnetværket for it
 
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16
Innovecs
 
Introductory func prog
Oleksandr Khomenko
 
Why functional programming in C# & F#
Riccardo Terrell
 
Go Beyond Higher Order Functions: A Journey into Functional Programming
Lex Sheehan
 
Functional Programming Fundamentals
OleksiyTereshchenko
 
Programming Paradigms
Janeve George
 

Recently uploaded (20)

PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PDF
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Digital Circuits, important subject in CS
contactparinay1
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Ad

Functional Programming 之二三事

  • 1. Functional Programming Leeheng July 31, 2009
  • 2. Functional Bet Programming a Leeheng July 31, 2009
  • 3. Agenda About Myself Why This Topic Programming Paradigm 10min PL Moving On Why FP Matters IP VS DP Function, Lambda Calculus High Order Function, Currying No Side Effect, Referential Transparent Least Surprise, No Update 25min Recursion, Lazy Evaluation Pattern Matching, Tail recursion Memoization, Closure Loop Helper Example Story 25min Reference Question 2
  • 4. Agenda About Myself Why This Topic Programming Paradigm 10min PL Moving On Why FP Matters IP VS DP Function, Lambda Calculus High Order Function, Currying No Side Effect, Referential Transparent Least Surprise, No Update 25min Recursion, Lazy Evaluation Pattern Matching, Tail recursion Memoization, Closure Loop Helper Example Story 25min Reference Question 2
  • 5. Agenda About Myself Why This Topic Programming Paradigm 10min PL Moving On Why FP Matters IP VS DP Function, Lambda Calculus High Order Function, Currying No Side Effect, Referential Transparent Least Surprise, No Update 25min Recursion, Lazy Evaluation Pattern Matching, Tail recursion Memoization, Closure Loop Helper Example Story 25min Reference Question 2
  • 6. Agenda About Myself Why This Topic Programming Paradigm 10min PL Moving On Why FP Matters IP VS DP Function, Lambda Calculus High Order Function, Currying No Side Effect, Referential Transparent Least Surprise, No Update 25min Recursion, Lazy Evaluation Pattern Matching, Tail recursion Memoization, Closure Loop Helper Example Story 25min Reference Question 2
  • 7. ABOUT MYSELF Leeheng Ma Y! 2009 Search Team Intern NCCU MIS undergraduate Interests : Algorithm, Programming language, Compiler, Web Technology. 3
  • 9. WHY THIS TOPIC .... 4
  • 10. WHY THIS TOPIC .... Programming Language RD 4
  • 11. Programming Paradigm Programming paradigm is a Fundamental style of computer programming. 5
  • 12. Programming Paradigm Programming paradigm is a Fundamental style of computer programming. For solving Software Engineering Problems. 5
  • 13. Programming Paradigm Programming paradigm is a Fundamental style of computer programming. For solving Software Engineering Problems. Programming Paradigm SHIFT 5
  • 14. Think Different • A language that doesn't affect the way you think about programming, is not worth knowing. --Alan Perlis 6
  • 15. Think Different • A language that doesn't affect the way you think about programming, is not worth knowing. --Alan Perlis 6
  • 16. Think Different • A language that doesn't affect the way you think about programming, is not worth knowing. --Alan Perlis 6
  • 17. HOW MANY YOU KNOW ? • Concurrent • Imperative • Declarative • Functional • Procedural Programming • Prototype-based • Event-driven • Aspect-Oriented • Object-Oriented • Meta-Programming • Generic 7
  • 18. HOW MANY YOU KNOW ? ... Orz ..... ... 7
  • 19. WHERE PL MOVING ON ? 8
  • 20. WHERE PL MOVING ON ? 8
  • 21. WHERE PL MOVING ON ? 8
  • 22. WHERE PL MOVING ON ? 8
  • 23. WHERE PL MOVING ON ? 8
  • 24. WHERE PL MOVING ON ? 8
  • 25. WHERE PL MOVING ON ? 8
  • 26. WHERE PL MOVING ON ? 8
  • 27. WHERE PL MOVING ON ? 8
  • 28. WHERE PL MOVING ON ? 8
  • 29. WHERE PL MOVING ON ? 8
  • 30. WHERE PL MOVING ON ? 8
  • 31. WHERE PL MOVING ON ? 8
  • 32. WHERE PL MOVING ON ? 8
  • 34. WHY FP MATTERS • Python, Ruby, Perl all use ideas form FP • Y! ’s Hadoop and G ‘s MapReduce are large scale FP 9
  • 35. WHY FP MATTERS • Python, Ruby, Perl all use ideas form FP • Y! ’s Hadoop and G ‘s MapReduce are large scale FP Modularity Interchangeable parts Easy test and debug Easy optimization Function as data • No Side Effect Pattern Matching Concurrent Processing • High Order Function Closure Lazy Evaluation Referential transparency 9
  • 36. 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. The focus is on what, not how 10
  • 37. IP VS FP OO C+ P • Imperative Programming Java + – 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. The focus is on what, not how 10
  • 38. IP VS FP OO C+ P • Imperative Programming Java + – Computation Executing statements to change state. – Program Consists of a sequence of commands. g Lisp Ha E rlan • Functional Programming ske ll – Computation Evaluation of expressions. – Expression Formed by using functions to combine basic values. The focus is on what, not how 10
  • 40. Create Sandwich Imperative 1. Take a bread 2. Spread bread with butter 3. Put cheese on the bread 4. return sandwich Functional 11
  • 41. Create Sandwich Imperative 1. Take a bread 2. Spread bread with butter 3. Put cheese on the bread 4. return sandwich Functional return put ( cheese, spread(butter, bread) ) 11
  • 42. Features 12
  • 43. Function is ? 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. 12
  • 44. Function is ? 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). 12
  • 45. Function is ? 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). 12
  • 46. Function is ? 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!! 12
  • 47. Lambda Calculus The λ-calculus was developed by the logician Alonzo Church in 1930’s as a tool to study functions and computability. 13
  • 48. λ Calculus Equivalent to Turing Machines Turing 1937 Equivalent to recursive functions Kleene 1936 (λ x. x + 2) 14
  • 49. λ Calculus Equivalent to Turing Machines Turing 1937 Equivalent to recursive functions Kleene 1936 (λ x. x + 2) = (x) { return x + 2} 14
  • 50. λ Calculus Equivalent to Turing Machines Turing 1937 Equivalent to recursive functions Kleene 1936 (λ x. x + 2) = (x) { return x + 2} (λ x. x + 2) 3 = 5 14
  • 51. λ Calculus Equivalent to Turing Machines Turing 1937 Equivalent to recursive functions Kleene 1936 (λ f. f 3)(λ x. x+2) = ? 14
  • 52. λ Calculus Equivalent to Turing Machines Turing 1937 Equivalent to recursive functions Kleene 1936 (λ f. f 3)(λ x. x+2) = ? = (λ x. x + 2) 3 =3+2 14
  • 53. High Order Function • Functions take other functions as parameters • Functions return functions as results 15
  • 54. High Order Function • Functions take other functions as parameters ∑ f(x) x∈L • Functions return functions as results 15
  • 55. High Order Function • Functions take other functions as parameters ∑ f(x) x∈L • Functions return functions as results d f(x) dx = f’(x) 15
  • 57. Mathematics OK, no more mathematics. 16
  • 64. Currying ( ) AJAX callback function 18
  • 65. No Side Effect Output is solely dependent of input. input output Pure Function 19
  • 66. No Side Effect Output is solely dependent of input. States input output Impure Function With Assignment 19
  • 67. No Side Effect Output is solely dependent of input. States input output Impure Function With Assignment Can replace f(x) + f(x) with 2*f(x)? 19
  • 68. Referential Transparent If the function f is referential transparent. 20
  • 69. Referential Transparent If the function f is referential transparent. What is this? 20
  • 70. Referential Transparent What is this? Definition: If Function result depends only on the values of its parameters. 20
  • 71. Referential Transparent What is this? Definition: If Function result depends only on the values of its parameters. Murmur: This concept occurs in mathematics, but it is broken by imperative programming languages. 20
  • 72. Side Effect Consider the following C/Java function f: 21
  • 73. Side Effect Consider the following C/Java function f: f change the state outside the function. 21
  • 74. Principle Of Least Surprise 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) 22
  • 75. No Update On Variables Definition: Variables are similar to Variables in mathematics, they hold a value but they can’t be updated. Variables only assigned once. Pure 23
  • 76. No Update On Variables Definition: Variables are similar to Variables in mathematics, they hold a value but they can’t be updated. Variables only assigned once. Pure 23
  • 77. No Update On Variables Definition: Variables are similar to Variables in mathematics, they hold a value but they can’t be updated. Variables only assigned once. So...We don’t need to care call by value, call by reference...etc. Pure 23
  • 78. No Update On Variables Definition: Variables are similar to Variables in mathematics, they hold a value but they can’t be updated. Variables only assigned once. So...We don’t need to care call by value, call by reference...etc. Pure 23
  • 79. Recursion Basics How to Loop? Functional programs are usually H . (with map, fold, filter) Pure 24
  • 80. Recursion Basics How to Loop? Functional programs are usually Heavily Recursive. (with map, fold, filter) Pure 24
  • 81. Recursion Basics How to Loop? Functional programs are usually Heavily Recursive. (with map, fold, filter) Iteration.isEqualTo( Recursive); Pure 24
  • 82. Efficiency Early: It is true... Now: Tail Recursion. Lazy Evaluation. Memoization Common Subexpression Elimination Parallel Computing 25
  • 83. Efficiency Early: It is true... Now: Tail Recursion. Lazy Evaluation. Memoization Common Subexpression Elimination Parallel Computing 25
  • 84. Efficiency Early: It is true... Now: Tail Recursion. != Lazy Evaluation. Memoization Common Subexpression Elimination Parallel Computing 25
  • 85. Efficiency Early: It is true... Now: Tail Recursion. Lazy Evaluation. Memoization Common Subexpression Elimination Parallel Computing 25
  • 86. Efficiency Early: It is true... Now: Tail Recursion. Lazy Evaluation. Memoization Common Subexpression Elimination Parallel Computing 25
  • 87. Chat in Pugs Project 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 sec 19: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 ok 19: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. enjoy 19:14 < malaire> that's quite fast development :) 19:14 < autrijus> :) 26
  • 88. Lazy Evaluation 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 27
  • 89. Lazy Evaluation 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 27
  • 90. Lazy Evaluation lazy evaluation is the technique of delaying a computation until the result is required. Benefits: In Haskell, we don’t run S1 = EXPR 1(); S1 and S2 before we call Concatenate, we S2 = EXPR 2(); even don’t know which S2 = Concatenate(S1, S2); one evaluate first! Pure 27
  • 91. Lazy Evaluation lazy evaluation is the technique of delaying a computation until the result is required. Benefits: In Haskell, we don’t run S1 = EXPR 1(); S1 and S2 before we call Concatenate, we S2 = EXPR 2(); even don’t know which S2 = Concatenate(S1, S2); one evaluate first! Benefits: Pure 27
  • 92. Pattern Matching A Good Picture Can Tell Every Thing! 28
  • 94. Tail Recursion Stack fac 5 5 * (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 Time 29
  • 96. Tail Recursion Stack fac 5 tailfac 5 1 tailfac 4 5 * 1 tailfac 3 4 * 5 * 1 tailfac 2 3 * 4 * 5 * 1 tailfac 1 2 * 3 * 4 * 5 * 1 tailfac 0 1 * 2 * 3 * 4 * 5 * 1 . . 120 Time 29
  • 97. Tail Recursion Stack fac 5 tailfac 5 1 tailfac 4 5 * 1 tailfac 3 4 * 20 5 * 1 tailfac 2 3 * 60 4 * 5 * 1 tailfac 1 2 * 120 3 * 4 * 5 * 1 tailfac 0 1 * 120 2 * 3 * 4 * 5 * 1 . . 120 Time 29
  • 98. Tail Recursion Stack fac 5 tailfac 5 1 tailfac 4 5 * 1 tailfac 3 4 * 20 5 * 1 tailfac 2 3 * 60 4 * 5 * 1 tailfac 1 2 * 120 3 * 4 * 5 * 1 tailfac 0 1 * 120 2 * 3 * 4 * 5 * 1 . . Tail Recursion can be Time 120 optimize to loop!! 29
  • 99. Memoization 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. 30
  • 100. Memoization 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. 30
  • 102. Closure In C New or Malloc. 31
  • 103. Closure In C But Global is 31
  • 104. Closure In C Another issue: scope static and dynamic. 31
  • 105. Closure In C Another issue: scope static and dynamic. Global I Am Symbol Table 31
  • 106. Closure In C Another issue: scope static and dynamic. Global Local I Am I Am Symbol Table Symbol Table 31
  • 107. Closure In C Another issue: scope static and dynamic. Global I Am Symbol Table 31
  • 108. Closure In C Another issue: scope static and dynamic. 31
  • 109. Closure In C Another issue: scope static and dynamic. 31
  • 110. Closure In C Another issue: scope static and dynamic. 31
  • 111. Loop Helper Not only Recursion, but also Loop Helper? Recursion : divided and conquer Loop : don’t do that so complicate 32
  • 113. Folding Alias : reduce Operator Initial value List 33
  • 117. Mapping 34
  • 118. Mapping 34
  • 119. Mapping 34
  • 120. Mapping a, b, c, ..., z f(a), f(b), f(c), ..., f(z) Function f() 34
  • 121. Mapping 34
  • 122. Filtering Definition: if (p?) w, then send w to output a, b, c, ..., z a’, b’, c’, ..., z’ Function f() 35
  • 123. Filtering Definition: if (p?) w, then send w to output a, b, c, ..., z a’, b’, c’, ..., z’ Function f() 35
  • 124. Quick Sort 36
  • 125. Quick Sort 36
  • 126. Quick Sort 36
  • 127. Quick Sort 36
  • 128. Insert Sort 37
  • 129. Insert Sort 37
  • 130. Insert Sort 37
  • 131. Insert Sort 37
  • 132. Insert Sort 37
  • 133. Story Paul Graham Develop Y! Store by Lisp. Develop Perl6 by Haskell. “ Lisp ” by Beyond Java MIT CS 6.001 Structure and Interpretation of Computer Programs 38
  • 134. 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
  • 135. 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
  • 136. Question ? 41