Functional Programming Basics - PowerPoint PPT Presentation

About This Presentation
Title:

Functional Programming Basics

Description:

Functional Programming Basics Correctness Clarity Efficiency cs7120 (Prasad) L1-FP-HOF * * Tail recursion : convertible to iteration (Cf. SICP s Recursive vs ... – PowerPoint PPT presentation

Number of Views:117
Avg rating:3.0/5.0
Slides: 36
Provided by: TK198
Learn more at: http://cecs.wright.edu
Category:

less

Transcript and Presenter's Notes

Title: Functional Programming Basics


1
Functional Programming Basics
  • Correctness gt Clarity gt Efficiency

2
  • Function Definition
  • Equations Recursion
  • Higher-order functions
  • Function Application
  • Computation by expression evaluation
  • Choices parameter passing
  • Reliability
  • Types
  • Strong typing, Polymorphism, ADTs.
  • Garbage Collection

3
Imperative Style vs Functional Style
  • Imperative programs
  • Description of WHAT is to be computed is
    inter-twined with HOW it is to be computed.
  • The latter involves organization of data and the
    sequencing of instructions.
  • Functional Programs
  • Separates WHAT from HOW.
  • The former is programmers responsibility the
    latter is interpreters/compilers responsibility.

4
  • Functional Style
  • Value to be computed a b c
  • Imperative Style
  • Recipe for computing the value
  • Intermediate Code
  • T a b T T c
  • T b c T a T
  • Accumulator Machine
  • Load a Add b Add c
  • Stack Machine
  • Push a Push b Add Push c Add

5
GCD functional vs imperative
  • fun gcd(m,n)
  • if m0 then n
  • else gcd(n mod m, m)
  • function gcd(m,n int) int
  • var pmint
  • begin while mltgt0 do
  • begin
  • pm m m n mod m n pm
  • end
  • return n
  • end

6
Pitfalls Sequencing
  • (define (factorial n)
  • (define (iter prod counter)
  • (if (gt counter n) prod
  • (iter ( counter prod)
  • ( counter 1) ) ))
  • (iter 1 1)
  • )

7
  • (define (factorial n)
  • (let ((prod 1)(counter 1))
  • (define (iter)
  • (if (gt counter n) prod
  • (begin
  • (set! prod ( counter prod))
  • (set! counter ( 1 counter))
  • (iter))
  • ))
  • ))

8
Function
  • A function f from domain A to co-domain B,
    denoted f A -gt B, is a map that associates with
    every element a in A, a unique element b in B,
    denoted f(a).
  • Cf. Relation, multi-valued function, partial
    function,
  • In mathematics, the term function usually
    refers to a total function in computer science,
    the term function usually refers to a partial
    function.

9
Representation of functions
  • Intensional Rule of calculation
  • fun double n 2 n
  • fun double n n n
  • Extensional Behavioral (Table)
  • Equality
  • f g iff for all x f(x) g(x)

10
Expression Evaluation Reduction
  • fun double x x x
  • double ( 3 2)
  • double(6) (32) (32) (32) o
  • 6 6 6 (3 2) 6
    o
  • Applicative-Order Normal-Order Lazy
  • (call by value) (call by name)
    (call by need)

11
Role of variable
  • In functional style, a variable stands for an
    arbitrary value, and is used to abbreviate an
    infinite collection of equations.
  • 0 0 0
  • 0 1 1
  • for all x 0 x x
  • In imperative style, a variable is a location
    that can hold a value, and which can be changed
    through an assignment.
  • x x 1
  • Functional variable can be viewed as assign-only-
    once imperative variable.

12
Referential Transparency
  • The only thing that matters about an expression
    is its value, and any sub-expression can be
    replaced by any other expression equal in value.
  • The value of an expression is independent of its
    position only provided we remain within the
    scopes of the definitions which apply to the
    names occurring in the expression.

13
Examples
  • let x 5 in
  • x let x 4 in x x
  • val y 2 val y 6
  • var x int
  • begin
  • x x 2 x x 1
  • end
  • address of x value stored in location for
    x

14
  • (x2) /\ (xygt2) (2ygt2)
  • vs
  • fun f (x int) int
  • begin y y 1
  • return ( x y)
  • end
  • (y0) /\ (z0) /\ (f(y)f(z))
  • false
  • (y0) /\ (z0) /\ (f(z)f(z))
  • / (y0) /\ (z0) /\ (f(z)1)

15
  • Common sub-expression elimination is an
    incorrect optimization without referential
    transparency.
  • In functional style
  • E E let x E in x x
  • In imperative style
  • return (x x)
  • /
  • y x return (y y)
  • Parallel evaluation of sub-expressions possible
    with referential transparency.

16
By GUY STEELE
17
Strict vs Non-strict
  • A function is strict if it returns well-defined
    results only when the inputs are well-defined.
  • E.g., In C, and are strict, while
    and are not.
  • E.g., In Ada, and and or are strict, while
    and then and or else are not.
  • E.g., constant functions are non-strict if called
    by name, but are strict if called by value.

18
Traditional Benefits of Programming in a
Functional Language
  • Convenient to code symbolic computations and list
    processing applications.
  • Automatic storage management
  • Improves program reliability.
  • Enhances programmer productivity.
  • Abstraction through higher-order functions and
    polymorphism.
  • Facilitates code reuse.
  • Ease of prototyping using interactive development
    environments.

19
Global Summary
Programming Languages
Imperative
Functional
Logic
C, Pascal
Prolog
Dynamically Typed (Meta-programming)
Statically Typed (Type Inference/Reliable)
LISP, Scheme
Lazy Eval / Pure
Eager Eval / Impure
Haskell
SML
20
Higher-Order Functions
21
Higher-Order Functions
  • A function that takes a function as argument
    and/or returns a function as result is called a
    higher-order function or a functional.
  • ML/Scheme treat functions as first-class
    (primitive) values.
  • Can be supplied as input to functions.
  • Not allowed in Ada.
  • Can be created through expression evaluation.
  • Not allowed in C/Java/LISP.
  • Can be stored in data structures.

22
Nested Functional Static Scoping
  • fun f x
  • let
  • val g fn y gt 8 x y
  • in g
  • end
  • val h f 5
  • h 2
  • Breaks stack-based storage allocation Requires
    heap-based storage allocation and garbage
    collection (Closures)

23
ML function definitions
  • fun elem_to_list
  • elem_to_list (ht)
  • h (elem_to_list t)
  • elem_to_list a a
  • fun inc_each_elem
  • inc_each_elem (ht)
  • (h1) (inc_each_elem t)
  • inc_each_elem 1,2,3 2,3,4

24
Abstracting Patterns of Recursion
  • fun map f
  • map f (ht)
  • (f h)(map f t)
  • fun elem_to_list x
  • map (fn x gt x) x
  • val inc_each_elem
  • map (fn x gt x1)

25
Functionals Reusable modules
  • Libraries usually contain functionals that
    can be customized.
  • sort order list
  • Can be used for
  • descending_order_sort
  • ascending_order_sort
  • sort_on_length
  • sort_lexicographically
  • sort_on_name
  • sort_on_salary
  • ...

26
Orthogonality
  • Instead of defining related but separate
    functions such as
  • remove-if remove-if-not
  • process_till_p process_till_not_p
  • define one generalized functional complement.
  • Refer to CommonLISP vs Scheme

27
Currying
  • fun plus (x, y) x y
  • fun add x y x y
  • plus (5,3) 8
  • add 5 3 8
  • add 5 (fn x gt 5x)
  • Curried functions are higher-order functions that
    consume their arguments lazily.
  • All ML functions are curried !

28
Significance of Curried Functions
  • Supports partial evaluation.
  • Useful for customizing (instantiating) general
    purpose higher-order functions (generics).
  • Succinct definitions.
  • Denotational (Semantics) Specifications.
  • One-argument functions sufficient.
  • All ML functions are unary.

29
  • fun curry f
  • fn x gt (fn y gt f(x,y))
  • fun uncurry f
  • fn (x,y) gt (f x y)
  • curry (uncurry f) f
  • uncurry (curry f) f
  • (Higher-order functions)

30
Classification of functions
  • Primitive
  • , , - , etc.
  • Higher-order
  • Hierarchical
  • (sort order list),(filter pred list)
  • Self-applicable
  • map , id (E.g., (map (map f)) )
  • fun double f f o f

  • composition

31
From Spec. to Impl.
  • Spec
  • (sqrt x) gt 0 /\ (sqrt x)2 x
  • Computable Spec
  • (sqrt x) gt 0 /\
  • abs((sqrt x)2 - x) lt eps
  • Improving Approximations (Newtons method)
  • y(n1) (y(n) x / y(n)) / 2

32
  • fun improve x y
  • ( y x / y) / 2.0
  • val eps 1.0e5
  • fun satis x y
  • abs( yy - x) lt eps
  • fun until p f y
  • if p y then y
  • else until p f (f y)
  • fun sqrt x
  • until (satis x) (improve x) 1.0

33
ML Meta Language
  • Initial Domains of Application
  • Formal Specification of Languages
  • Theorem Proving
  • Theorems are values (terms) of an ADT.
  • Theorems can only be constructed using the
    functions supported by the ADT (no spoofing).
  • ML is a mathematically clean modern programming
    language for the construction of readable and
    reliable programs.
  • Executable Specification.

34
  • Symbolic Values
  • Recursive Definitions
  • Higher-Order Functions
  • Strongly Typed
  • Static Type Inference
  • Polymorphic Type System
  • Automatic Storage Management
  • Pattern Matching
  • ADTs Modules and Functors
  • Functional Imperative features

35
  • fun len 0
  • len (xxs)
  • 1 len xs
  • (define (len xs)
  • (if (null? xs)
  • 0
  • ( 1 (len (cdr xs)))
  • )
  • )
Write a Comment
User Comments (0)
About PowerShow.com