Functional Programming Universitatea Politehnica Bucuresti 2007-2008 Adina Magda Florea

Slides:



Advertisements
Similar presentations
Example of Constructing the DAG (1)t 1 := 4 * iStep (1):create node 4 and i 0 Step (2):create node Step (3):attach identifier t 1 (2)t 2 := a[t 1 ]Step.
Advertisements

Automatic Verification Book: Chapter 6. What is verification? Traditionally, verification means proof of correctness automatic: model checking deductive:
Elements of Lambda Calculus Functional Programming Academic Year Alessandro Cimatti
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.
Solving Problem by Searching
The Assembly Language Level
Factoring Polynomials
David Evans CS150: Computer Science University of Virginia Computer Science Lecture 39: Lambda Calculus.
Introduction to C Programming
1 Pass Compiler 1. 1.Introduction 1.1 Types of compilers 2.Stages of 1 Pass Compiler 2.1 Lexical analysis 2.2. syntactical analyzer 2.3. Code generation.
Review: Search problem formulation
CS 536 Spring Intermediate Code. Local Optimizations. Lecture 22.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
מבוא מורחב - שיעור 2 1 Lecture 2 - Substitution Model (continued) - Recursion - Block structure and scope (if time permits)
Intermediate Code. Local Optimizations
16.5 Introduction to Cost- based plan selection Amith KC Student Id: 109.
Describing Syntax and Semantics
Introduction to C Programming
LIAL HORNSBY SCHNEIDER
Query Processing Presented by Aung S. Win.
Fundamentals of Python: From First Programs Through Data Structures
Genetic Programming.
Systems and Matrices (Chapter5)
TH EDITION Copyright © 2013, 2009, 2005 Pearson Education, Inc. 1 1 Equations and Inequalities Copyright © 2013, 2009, 2005 Pearson Education,
10/12/20151 GC16/3C11 Functional Programming Lecture 3 The Lambda Calculus A (slightly) deeper look.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
© Kenneth C. Louden, Chapter 11 - Functional Programming, Part III: Theory Programming Languages: Principles and Practice, 2nd Ed. Kenneth C. Louden.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
P.1 Real Numbers and Algebraic Expressions. Negative numbers Units to the left of the origin are negative. Positive numbers Units to the right of the.
Functional Programming With examples in F#. Pure Functional Programming Functional programming involves evaluating expressions rather than executing commands.
Advanced Computer Architecture and Parallel Processing Rabie A. Ramadan http:
Chapter Fifteen: Functional Programming Languages Lesson 12.
1 Code optimization “Code optimization refers to the techniques used by the compiler to improve the execution efficiency of the generated object code”
© Kenneth C. Louden, Chapter 11 - Functional Programming, Part III: Theory Programming Languages: Principles and Practice, 2nd Ed. Kenneth C. Louden.
1 Formal Semantics. 2 Why formalize? ML is tricky, particularly in corner cases generalizable type variables? polymorphic references? exceptions? Some.
Basic Problem Solving Search strategy  Problem can be solved by searching for a solution. An attempt is to transform initial state of a problem into some.
College Algebra Sixth Edition James Stewart Lothar Redlin Saleem Watson.
Basic Scheme February 8, 2007 Compound expressions Rules of evaluation Creating procedures by capturing common patterns.
Types and Programming Languages Lecture 11 Simon Gay Department of Computing Science University of Glasgow 2006/07.
Advanced Functional Programming Tim Sheard 1 Lecture 17 Advanced Functional Programming Tim Sheard Oregon Graduate Institute of Science & Technology Lecture:
Arvind Computer Science and Artificial Intelligence Laboratory M.I.T. L04Ext-1 September 21, 2006http:// Some more thoughts.
Haskell Introduction CSCE 314 Spring CSCE 314 – Programming Studio Historical Background 1930s: Alonzo Church develops the lambda calculus, a simple.
Chapter 18 Query Processing and Optimization. Chapter Outline u Introduction. u Using Heuristics in Query Optimization –Query Trees and Query Graphs –Transformation.
ELEC692 VLSI Signal Processing Architecture Lecture 12 Numerical Strength Reduction.
Compiler Construction Lecture Five: Parsing - Part Two CSC 2103: Compiler Construction Lecture Five: Parsing - Part Two Joyce Nakatumba-Nabende 1.
6/21/20161 Programming Languages and Compilers (CS 421) Reza Zamani Based in part on slides by Mattox Beckman,
Introduction to Parsing
Functional Programming
Unit – 3 :LAMBDA CALCULUS AND FUNCTIONAL PROGRAMMING
Basic Scheme February 8, 2007 Compound expressions Rules of evaluation
CSE341: Programming Languages Lecture 14 Thunks, Laziness, Streams, Memoization Dan Grossman Spring 2017.
More on Lambda Calculus
CSE341: Programming Languages Lecture 14 Thunks, Laziness, Streams, Memoization Dan Grossman Winter 2013.
Closures and Streams cs784(Prasad) L11Clos
CSE341: Programming Languages Lecture 14 Thunks, Laziness, Streams, Memoization Zach Tatlock Winter 2018.
CSE341: Programming Languages Lecture 14 Thunks, Laziness, Streams, Memoization Dan Grossman Spring 2013.
Propositional Calculus: Boolean Algebra and Simplification
Programming Languages and Compilers (CS 421)
CSE341: Programming Languages Lecture 14 Thunks, Laziness, Streams, Memoization Dan Grossman Spring 2016.
CSE341: Programming Languages Lecture 14 Thunks, Laziness, Streams, Memoization Dan Grossman Autumn 2017.
CSE341: Programming Languages Lecture 14 Thunks, Laziness, Streams, Memoization Dan Grossman Autumn 2018.
Copyright © 2017, 2013, 2009 Pearson Education, Inc.
6.001 SICP Further Variations on a Scheme
Announcements Exam 2 on Friday, November 2nd Topics
L Calculus.
Copyright © Cengage Learning. All rights reserved.
Introduction to the Lab
Brett Wortzman Summer 2019 Slides originally created by Dan Grossman
CSE341: Programming Languages Lecture 14 Thunks, Laziness, Streams, Memoization Dan Grossman Spring 2019.
Presentation transcript:

Functional Programming Universitatea Politehnica Bucuresti Adina Magda Florea

Lecture No. 12 Analysis and Efficiency of Functional Programs Reduction strategies and lazy evaluation

1. Reduction strategies and lazy evaluation Programming is not only about writing correct programs but also about writing fast ones that require little memory Aim: how Haskell programs are commonly executed on a real computer a foundation for analyzing time and space usage Every implementation of Haskell more or less closely follows the execution model of lazy evaluation

1.1 Reduction Executing a functional program, i.e. evaluating an expression means to repeatedly apply function definitions until all function applications have been expanded Implementations of modern Functional Programming languages are based on a simplification technique called reduction.

Expression Syntax analysis Type analysis Reduction Value Syntactic error Type error Evaluation error Evaluation in a strongly typed language EVALUATIONEVALUATION The evaluation of an expression passes through three stages Only those expression which are syntactically correct and well typed are submitted for reduction

What is reduction? Given a set of rules R 1, R 2, …, R n (called reduction rules) and an expression e Reduction is the process of repeatedly simplifying e using the given reduction rules e  e 1 R i1  e 2 R i2 ….  e k R ik,R ij  {R 1, R 2, …, R n } until no rule is applicable e k is called the normal form of e It is the simplest form of e Expression Reduction Normal form

2 types of reduction rules Built-in rules: addition, substraction, multiplication, division User supplied rules: square x = x * x double x = x + x sum [ ] = 0 sum (x:xs) = x + sum xs f x y = square x + square y

1.2 Reduction at work Each reduction step replaces a subexpression by an equivalent expression by applying one of the 2 types of rules f x y = square x + square y f 3 4  (square 3) + (square 4) (f)  (3*3) + (square 4)(square)  9 + (square 4)(*)  9 + (4*4)(square)  (*)  25(+)

Reduction rules Every reduction replaces a subexpression, called reducible expression or redex for short, with an equivalent one, either by appealing to a function definition (like for square) or by using a built-in function like (+). An expression without redexes is said to be in normal form. The fewer reductions that have to be performed, the faster the program runs. We cannot expect each reduction step to take the same amount of time because its implementation on real hardware looks very different, but in terms of asymptotic complexity, this number of reductions is an accurate measure.

Alternate reductions

Possible ways of evaluating square

Comments There are usually several ways for reducing a given expression to normal form Each way corresponds to a route in the evaluation tree: from the root (original expression) to a leaf (reduced expression) There are three different ways for reducing square (3+7) Questions: Are all the answers obtained by following distinct routes identical? Which is the best route? Can we find an algorithm which always follows the best route?

Q&A Q: Are all the values obtained by following distinct routes identical? A: If two values are obtained by following two different routes, then these values must be identical Q: Which is the best route? Ideally, we are looking for the shortest route. Because this will take the least number of reduction steps and, therefore, is the most efficient.

Q&A Q: Can we find an algorithm which always follows the best route? In any tree of possible evaluations, there are usually two extremely interesting routes based on: An Eager Evaluation Strategy A Lazy Evaluation Strategy

1.3 Eager evaluation Given an expression such as: f a where f is a function and a is an argument. The Lazy Evaluation strategy reduces such an expression by attempting to apply the definition of f first. The Eager Evaluation Strategy reduces this expression by attempting to simplify the argument a first.

Example of Eager Evaluation

Example of Lazy Evaluation

1.4 A&D of reduction strategies LAZY EVALUATION = Outer-most Reduction Strategy Reduces outermost redexes = redexes that are not inside another redex. EAGER EVALUATION = Inner-most Reduction Strategy Reduces innermost redexes An innermost redex is a redex that has no other redex as subexpression inside. Advantages and drawbacks

Repeated Reductions of Subexpressions Eager Evaluation is better because it did not repeat the reduction of the subexpression (3+7)!

Repeated Reductions of Subexpressions Eager Evaluation requires 102 reductions Lazy Evaluation requires 202 reductions The Eager Strategy did not repeat the reduction of the subexpression sum [1..100])!

Performing Redundant Computations first (2+2, square 15) Lazy Evaluation  2 + 2(first)  4(+) Eager Evaluation  first (4, square 15)(+)  first(4, 225)(square)  first(4, 225)(*)  4(first)  Lazy evaluation is better as it avoids performing redundant computations

Termination For some expressions like loop = 1 + loop no reduction sequence may terminate; they do not have a normal form. But there are also expressions where some reduction sequences terminate and some do not first (5, 1 / 0) Lazy Evaluation  5(first) Eager Evaluation  first(5, bottom)(/)  bottom(Attempts to compute 1/0)  Lazy evaluation is better as it avoids infinite loops in some cases

Eager evaluation Advantages: Repeated reductions of sub-expressions is avoided. Drawbacks: Have to evaluate all the parameters in a function call, whether or not they are required to produce the final result. It may not terminate.

Lazy evaluation Advantages: A sub-expression is not reduced unless it is absolutely essential for producing the final result. If there is any reduction order that terminates, then Lazy Evaluation will terminate. Drawbacks: The reductions of some sub-expressions may be unnecessarily repeated.

Duplicated Reduction of Subexpressions The reduction of the expression (3+4) is duplicated when we attempt to use lazy evaluation to reduce square (3+4) This problem arises for any definition where a variable on the left-hand side appears more than once on the right-hand side. square x = x * x cube x = x * x * x

1.5 Graph Reduction Aim: Keep All good features of Lazy Evaluation and at the same time avoiding duplicated reductions of sub-expressions. Method: By representing expressions as graphs so that all occurrences of a variable are pointing to the same value.

Graph Reduction Graph Reduction Strategy combines all the benefits of both Eager and Lazy evaluations with none of their drawbacks. *

Graph Reduction The outermost graph reduction of square (3 + 4) now reduces every argument at most once. For this reason, it always takes fewer reduction steps than the innermost reduction Sharing of expressions is also introduced with let and where constructs.

Graph Reduction for let Heron's formula for the area of a triangle with sides a, b and c: Let-bindings simply give names to nodes in the graph

Graph Reduction Any implementation of Haskell is in some form based on outermost graph reduction which thus provides a good model for reasoning about the asymptotic complexity of time and memory allocation The number of reduction steps to reach normal form corresponds to the execution time and the size of the terms in the graph corresponds to the memory used.

Reduction of higher order functions and currying id x = x a = id (+1) 41 twice f = f. f b = twice (+1) (13*3) where both id and twice are only defined with one argument. The solution is to see multiple arguments as subsequent applications to one argument - currying (.) :: (b->c)->(a->b)->(a->c) f. g = \x -> f (g x)

Reduction of higher order functions and currying Currying a = (id (+1)) 41 b = (twice (+1)) (13*3) To reduce an arbitrary application expression1 expression2, call-by-need first reduce expression1 until this becomes a function whose definition can be unfolded with the argument expression2. id x = x a= id (+1) 41 twice f = f. f b= twice (+1) (13*3)

Reduction of higher order functions and currying a = (id (+1)) 41 a  (id (+1)) 41 (a)  (+1) 41 (id)  42 (+)

Reduction of higher order functions and currying b = (twice (+1)) (13*3) b  (twice (+1)) (13*3) (b)  ((+1).(+1) ) (13*3) (twice)  (+1) ((+1) (13*3)) (.)  (+1) ((+1) 39) (*)  (+1) 40 (+)  41 (+)

Reduction of higher order functions and currying Functions are useful as data structures. In fact, all data structures are represented as functions in the pure lambda calculus, the root of all functional programming languages.