Cs7120 (Prasad)L1-FP-HOF1 Functional Programming Basics Correctness > Clarity > Efficiency.

Slides:



Advertisements
Similar presentations
1 Scheme and Functional Programming Aaron Bloomfield CS 415 Fall 2005.
Advertisements

Cs776 (Prasad)L4Poly1 Polymorphic Type System. cs776 (Prasad)L4Poly2 Goals Allow expression of “for all types T” fun I x = x I : ’a -> ’a Allow expression.
Programming Languages and Paradigms
Recap 1.Programmer enters expression 2.ML checks if expression is “well-typed” Using a precise set of rules, ML tries to find a unique type for the expression.
1 Programming Languages (CS 550) Lecture Summary Functional Programming and Operational Semantics for Scheme Jeremy R. Johnson.
Getting started with ML ML is a functional programming language. ML is statically typed: The types of literals, values, expressions and functions in a.
Functional Programming. Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends.
Lambda Calculus and Lisp PZ03J. Lambda Calculus The lambda calculus is a model for functional programming like Turing machines are models for imperative.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
1 Functional programming Languages And a brief introduction to Lisp and Scheme.
Cs7100(Prasad)L11Clos1 Closures and Streams. Contemporary Interest in Closures The concept of closures was developed in the 1960s and was first fully.
Functional Design and Programming Lecture 1: Functional modeling, design and programming.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
Chapter 15 Other Functional Languages. Copyright © 2007 Addison-Wesley. All rights reserved. Functional Languages Scheme and LISP have a simple syntax.
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 14 Functional Programming It is better to.
ISBN Chapter 15 Functional Programming Languages Mathematical Functions Fundamentals of Functional Programming Languages Introduction to.
Functional programming: LISP Originally developed for symbolic computing First interactive, interpreted language Dynamic typing: values have types, variables.
ISBN Chapter 15 Functional Programming Languages.
Functional Programming Professor Yihjia Tsai Tamkang University.
ISBN Chapter 15 Functional Programming Languages.
1 Lisp and Functional Languages Functional forms Referential transparency Function construction Function composition Mapping functions Designing functional.
Closures and Streams More on Evaluations CS784(pm)1.
CS 2104 : Prog. Lang. Concepts. Functional Programming I Lecturer : Dr. Abhik Roychoudhury School of Computing From Dr. Khoo Siau Cheng’s lecture notes.
Functional Programing Referencing material from Programming Language Pragmatics – Third Edition – by Michael L. Scott Andy Balaam (Youtube.com/user/ajbalaam)
PrasadCS7761 Haskell Data Types/ADT/Modules Type/Class Hierarchy Lazy Functional Language.
 The design of the imperative languages is based directly on the von Neumann architecture  Efficiency is the primary concern  Low-level specifications:
ISBN Chapter 15 Functional Programming Languages.
Runtime Environments Compiler Construction Chapter 7.
ISBN Chapter 15 Functional Programming Languages.
1 COMP313A Functional Programming (1). 2 Main Differences with Imperative Languages Say more about what is computed as opposed to how Pure functional.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 7.
10/16/2015IT 3271 All about binding n Variables are bound (dynamically) to values n values must be stored somewhere in the memory. Memory Locations for.
CSC 580 – Theory of Programming Languages, Spring, 2009 Week 9: Functional Languages ML and Haskell, Dr. Dale E. Parson.
Programming Languages and Paradigms Imperative Programming.
Functional Programming With examples in F#. Pure Functional Programming Functional programming involves evaluating expressions rather than executing commands.
Chapter Fifteen: Functional Programming Languages Lesson 12.
Compiling Functional Programs Mooly Sagiv Chapter 7
ISBN Chapter 15 Functional Programming Languages.
TIVDM2Functional Programming Language Concepts 1 Concepts from Functional Programming Languages Peter Gorm Larsen.
COMP313A Functional Programming (1)
1 Alex Proctor and Brian Lee for CSCI 431 at UNCA, Fall 2002 ML (Meta Language) a brief introduction Alex Proctor and Brian Lee For CSCI 431 at the University.
CS 2104 – Prog. Lang. Concepts Functional Programming II Lecturer : Dr. Abhik Roychoudhury School of Computing From Dr. Khoo Siau Cheng’s lecture notes.
CMSC 330: Organization of Programming Languages Maps and Folds Anonymous Functions.
Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real.
1 Programming Languages (CS 550) Lecture 4 Summary Functional Programming and Operational Semantics for Scheme Jeremy R. Johnson.
CS5205Haskell1 CS5205: Foundation in Programming Languages Basics of Functional Programming.
1 FP Foundations, Scheme In Text: Chapter Chapter 14: FP Foundations, Scheme Mathematical Functions Def: A mathematical function is a mapping of.
Cs3180 (Prasad)L156HOF1 Higher-Order Functions. cs3180 (Prasad)L156HOF2 Equivalent Notations (define (f x y) (… body …)) = (define f (lambda (x y) (…
3/8/20161 Programming Languages and Compilers (CS 421) Reza Zamani Based in part on slides by Mattox Beckman, as updated.
Cs776 (Prasad)L2HOF1 Higher-Order Functions. cs776 (Prasad)L2HOF2 Higher-Order Functions A function that takes a function as argument and/or returns a.
Functional Programming
CS314 – Section 5 Recitation 9
Operational Semantics of Scheme
Functional Programming
Type Checking and Type Inference
Functional Programming Languages
Functional Programming
ML: a quasi-functional language with strong typing
Scheme : variant of LISP
September 4, 1997 Programming Languages (CS 550) Lecture 6 Summary Operational Semantics of Scheme using Substitution Jeremy R. Johnson TexPoint fonts.
Closures and Streams cs784(Prasad) L11Clos
Important Concepts from Clojure
Important Concepts from Clojure
FP Foundations, Scheme In Text: Chapter 14.
Functional Programming Languages
Procedural vs Functional Style
Important Concepts from Clojure
Closures and Streams cs7100(Prasad) L11Clos
CSE 341 Lecture 11 b closures; scoping rules
Presentation transcript:

cs7120 (Prasad)L1-FP-HOF1 Functional Programming Basics Correctness > Clarity > Efficiency

cs7120 (Prasad)L1-FP-HOF2 Function Definition Equations ; Recursion Higher-order functions Function Application Computation by expression evaluation Choices : parameter passing  Reliability  Types  Strong typing, Polymorphism, ADTs.  Garbage Collection

cs7120 (Prasad)L1-FP-HOF3 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 programmer’s responsibility; the latter is interpreter’s/compiler’s responsibility.

cs7120 (Prasad)L1-FP-HOF4 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;

cs7120 (Prasad)L1-FP-HOF5 GCD : functional vs imperative fun gcd(m,n) = if m=0 then n else gcd(n mod m, m); function gcd(m,n: int) : int; var pm:int; begin while m<>0 do begin pm := m; m := n mod m; n := pm end; return n end;

cs7120 (Prasad)L1-FP-HOF6 Pitfalls : Sequencing (define (factorial n) (define (iter prod counter) (if (> counter n) prod (iter (* counter prod) (+ counter 1) ) )) (iter 1 1) )

cs7120 (Prasad)L1-FP-HOF7 (define (factorial n) (let ((prod 1)(counter 1)) (define (iter) (if (> counter n) prod (begin (set! prod (* counter prod)) (set! counter (+ 1 counter)) (iter)) ))

cs7120 (Prasad)L1-FP-HOF8 Function f A BA  B A BA function f from domain A to co-domain B, denoted f : A  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.

cs7120 (Prasad)L1-FP-HOF9 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)

cs7120 (Prasad)L1-FP-HOF10 Expression Evaluation : Reduction fun double x = x + x; double ( 3 * 2) double(6) (3*2) + (3*2) (3*2) + o (3 * 2) 6 + o Applicative-Order Normal-Order Lazy (call by value) (call by name) (call by need)

cs7120 (Prasad)L1-FP-HOF11 Role of variable In functional style, a variable stands for an arbitrary value, and is used to abbreviate an infinite collection of equations = = 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.

cs7120 (Prasad)L1-FP-HOF12 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.

cs7120 (Prasad)L1-FP-HOF13 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 Examples

cs7120 (Prasad)L1-FP-HOF14 (x=2) /\ (x+y>2) (2+y>2) vs fun f (x : int) : int ; begin y := y + 1; return ( x + y) end; (y=0) /\ (z=0) /\ (f(y)=f(z)) = false (y=0) /\ (z=0) /\ (f(z)=f(z)) =/= (y=0) /\ (z=0) /\ (f(z)=1)

cs7120 (Prasad)L1-FP-HOF15 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.

By GUY STEELE

cs7120 (Prasad)L1-FP-HOF17 Strict vs Non-strict strictA 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.

cs7120 (Prasad)L1-FP-HOF18 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.

cs7120 (Prasad)L1-FP-HOF19 Global Summary Programming Languages ImperativeFunctionalLogic Dynamically Typed (Meta-programming) Statically Typed (Type Inference/Reliable) Lazy Eval / Pure Eager Eval / Impure C, PascalProlog LISP, Scheme HaskellSML

cs7120 (Prasad)L1-FP-HOF20 Higher-Order Functions

cs7120 (Prasad)L1-FP-HOF21 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.

cs7120 (Prasad)L1-FP-HOF22 Nested Functional + Static Scoping fun f x = let val g = fn y => 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 )

cs7120 (Prasad)L1-FP-HOF23 ML function definitions fun elem_to_list [] = [] | elem_to_list (h::t) = [h] :: (elem_to_list t) elem_to_list [“a”] = [[“a”]] fun inc_each_elem [] = [] | inc_each_elem (h::t)= (h+1) :: (inc_each_elem t) inc_each_ elem [1,2,3] = [2,3,4]

cs7120 (Prasad)L1-FP-HOF24 Abstracting Patterns of Recursion fun map f [] = [] | map f (h::t) = (f h)::(map f t) fun elem_to_list x = map (fn x => [x]) x val inc_each_elem = map (fn x => x+1)

cs7120 (Prasad)L1-FP-HOF25 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...

cs7120 (Prasad)L1-FP-HOF26 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

cs7120 (Prasad)L1-FP-HOF27 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 => 5+x) Curried functions are higher-order functions that consume their arguments lazily. curriedAll ML functions are curried !

cs7120 (Prasad)L1-FP-HOF28 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. unaryAll ML functions are unary.

cs7120 (Prasad)L1-FP-HOF29 fun curry f = fn x => (fn y => f(x,y)) fun uncurry f = fn (x,y) => (f x y) curry (uncurry f) = f uncurry (curry f) = f (Higher-order functions)

cs7120 (Prasad)L1-FP-HOF30 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

cs7120 (Prasad)L1-FP-HOF31 From Spec. to Impl. Spec : (sqrt x) >= 0 /\ (sqrt x)^2 = x Computable Spec : (sqrt x) >= 0 /\ abs((sqrt x)^2 - x) < eps Improving Approximations (Newton’s method): y(n+1) = (y(n) + [x / y(n)]) / 2

cs7120 (Prasad)L1-FP-HOF32 fun improve x y = ( y + x / y) / 2.0 ; val eps = 1.0e~5; fun satis x y = abs( y*y - x) < 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;

cs7120 (Prasad)L1-FP-HOF33 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.

cs7120 (Prasad)L1-FP-HOF34 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

cs7120 (Prasad)L1-FP-HOF35 fun len [] = 0 | len (x::xs) = 1 + len xs (define (len xs) (if (null? xs) 0 (+ 1 (len (cdr xs))) )