Week 10: Loop Invariants, Code correctness Jimmy Voss Disclaimer: Some material may have been borrowed from both the Official Course slides as well as.

Slides:



Advertisements
Similar presentations
Programming with App Inventor Computing Institute for K-12 Teachers Summer 2012 Workshop.
Advertisements

Introduction to Algorithms Quicksort
Control Structures Selections Repetitions/iterations
Reasoning About Code; Hoare Logic, continued
Annoucements  Next labs 9 and 10 are paired for everyone. So don’t miss the lab.  There is a review session for the quiz on Monday, November 4, at 8:00.
Introduction to Computing Science and Programming I
Selection (decision) control structure Learning objective
Loops (Part 1) Computer Science Erwin High School Fall 2014.
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
Cosc 2150: Computer Organization Chapter 3: Boolean Algebra and Digital Logic.
ISBN Chapter 3 Describing Syntax and Semantics.
Week 3 – Sorting Machine, Stacks, Recursion, and Partial Maps Jimmy Voss Disclaimer: Not all material is original. Some is taken from the official course.
Proving the Correctness of Algorithms Algorithm Design and Analysis Week 2
1 Module 7 Halting Problem –Fundamental program behavior problem –A specific unsolvable problem –Diagonalization technique revisited Proof more complex.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
1 Lecture 7 Halting Problem –Fundamental program behavior problem –A specific unsolvable problem –Diagonalization technique revisited Proof more complex.
Describing Syntax and Semantics
CS241 PASCAL I - Control Structures1 PASCAL I - Control Structures Philip Fees CS241.
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
Recitation 1 Programming for Engineers in Python.
Fundamentals of Python: From First Programs Through Data Structures
Computer Science School of Computing Clemson University Discrete Math and Reasoning about Software Correctness Murali Sitaraman
1 What NOT to do I get sooooo Frustrated! Marking the SAME wrong answer hundreds of times! I will give a list of mistakes which I particularly hate marking.
More on Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7.
Fundamentals of Python: First Programs
Comp 249 Programming Methodology Chapter 15 Linked Data Structure - Part B Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
True or False: Boolean Expression Boolean expression are expressions which evaluate to "true" or "false“ Primary operators to combine expressions: && (and),
Week 2: Catalysts, Queues, Sorting, Component Coupling, and Inheritance Jimmy Voss Disclaimer: Not all material is original. Some is taken from the official.
Analyzing the Requirements with Formal Specifications Vienna Development Method Specification Language (VDM-SL) Book: Formal Software Development From.
Chapter 3 (Part 3): Mathematical Reasoning, Induction & Recursion  Recursive Algorithms (3.5)  Program Correctness (3.6)
© by Kenneth H. Rosen, Discrete Mathematics & its Applications, Sixth Edition, Mc Graw-Hill, 2007 Chapter 4 (Part 3): Mathematical Reasoning, Induction.
1 Inference Rules and Proofs (Z); Program Specification and Verification Inference Rules and Proofs (Z); Program Specification and Verification.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
COMP 116: Introduction to Scientific Programming Lecture 28: Midterm #2 Review.
Section 3.1: Proof Strategy Now that we have a fair amount of experience with proofs, we will start to prove more difficult theorems. Our experience so.
CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction.
Computer Science School of Computing Clemson University Discrete Math and Reasoning about Software Correctness Joseph E. Hollingsworth
CSE 222: Software Components in Engineering (SCE) – Introduction Instructor: Jimmy Voss Disclaimer: Not all material is original. Some is taken from the.
Recursive Descent Parsers Read and recognize the input (in order to translate it or evaluate it) Implicitly construct the derivation tree Design is driven.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
MATH 224 – Discrete Mathematics
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Reasoning about programs March CSE 403, Winter 2011, Brun.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students Introduction to branching.
22/11/ Selection If selection construct.
CS241 PASCAL I - Control Structures1 PASCAL Control Structures Modified Slides of Philip Fees.
CSE 201 – Elementary Computer Programming 1 Extra Exercises Sourceshttp://
1 Assertions. 2 A boolean expression or predicate that evaluates to true or false in every state In a program they express constraints on the state that.
31/01/ Selection If selection construct.
The Last Lecture CS 5010 Program Design Paradigms "Bootcamp" Lesson © Mitchell Wand, This work is licensed under a Creative Commons Attribution-NonCommercial.
Loop Invariants and Binary Search Chapter 4.4, 5.1.
Control flow Ruth Anderson UW CSE 160 Spring
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
CS122 – Quiz 2 Winter, 2013 Quiz Hints. Quiz 2 Hints Question 1 – working with the “if” statement  First, we did not fully explain the structure of the.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
Module 9: Operator overloading #1 2000/01Scientific Computing in OOCourse code 3C59 Module 9: Operator Overloading In this module we will cover Overloading.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Lecture 18 March 29, 2011 Formal Methods 3 CS 315 Spring Adapted from slides provided by Jason Hallstrom and Murali Sitaraman (Clemson)
CORRECTNESS ISSUES AND LOOP INVARIANTS Lecture 8 CS2110 – Fall 2014.
Searching and Sorting Searching algorithms with simple arrays
Chapter 4 (Part 3): Mathematical Reasoning, Induction & Recursion
Week 3 Part 2 Kyle Dewey.
Introduction to Programming for Mechanical Engineers (ME 319)
Primitive Data, Variables, Loops (Maybe)
Engineering Innovation Center
Conditions and Ifs BIS1523 – Lecture 8.
If selection construct
If selection construct
Language Constructs Construct means to build or put together. Language constructs refers to those parts which make up a high level programming language.
Presentation transcript:

Week 10: Loop Invariants, Code correctness Jimmy Voss Disclaimer: Some material may have been borrowed from both the Official Course slides as well as Anna Wolfe’s slides

Code Correctness Within the RESOLVE framework, code is considered to be correct if: 1.When you call any procedure / function, the requires clause (including convention / correspondence, etc.) is satisfied. 2.The procedure / function fulfills its contract (i.e., the ensures clause) when its contract, and the contracts of any procedures it calls are met. Notice, correct output does not mean correct code. Correct output is necessary but not sufficient.

Reasoning about Code RESOLVE formal comments give a means by which to reason about the correctness and behavior of code: – procedures/functions requires and ensures clauses – member functions of a class convention correspondence – recursive functions requires / ensures clauses decreases clause When code is correct, you can tell what a function call will do without looking at the code.

Loop Invariants The question remains: How do we reason about the behavior of a long, complicated loops? – Create a formal comment for the loop. – A loop runs multiple iterations. Thus the requires and ensures clauses must be the same. – Instead of using requires and ensures, we have a maintains clause. This clause states what is true at the beginning and end of each execution through the loop. – decreases clause – gives a non-negative valued expression that must get smaller after each iteration of the loop. This has the same purpose as in recursive functions.

Example global_procedure Concatenate ( alters Queue_Of_Integer & q1, alters Queue_Of_Integer & q2 ); /*! ensures q1 = #q1 * #q2 !*/

Example while ( q2.Length() > 0 ) /*! alters q1, q2 maintains q1 * q2 = #q1 * #q2 decreases |q2| !*/ { } How does this guarantee proper functionality? What code would I fill in here to get the desired functionality?

Example while ( q2.Length() > 0 ) /*! alters q1, q2 maintains q1 * q2 = #q1 * #q2 decreases |q2| !*/ { object catalyst Integer temp; q2.Dequeue( temp ); q1.Enqueue( temp ); }

Why Optimizations should Wait object Integer k = q2.Length() while ( k > 0 ) /*! alters q1, q2, k maintains q1 * q2 = #q1 * #q2 k = |q2| decreases k !*/ {... } The Introduction of k makes reasoning about the logic, and the loop invariant more complicated. However, it will help with the runtime.

Formal comments and loops Loops work on variables already in existence. – The preserves, alters, produces, and consumes modes need to be made explicit for variables operated on by the loop. – This is done in the formal comment for the loop. You should be able to reason about what a loop does based upon its formal comment.

Another Example global_function Real Power ( preserves Real x, preserves Integer p ); /*! requires p > 0 ensures Power = x ^ (p) !*/

Version 1 object Real result = x; object Integer this_p = 1; while ( this_p <= p/2 ) /*! preserves p alters result, this_p maintains result = x ^ (this_p) and this_p <= p and there exists k: integer (this_p = 2 ^ (k)) decreases p – this_p !*/ {... }...

Version 1 object Real result = x; object Integer this_p = 1; while ( this_p <= p/2 ) /*! preserves p alters result, this_p maintains result = x ^ (this_p) and this_p <= p and there exists k: integer (this_p = 2 ^ (k)) decreases p – this_p !*/ { this_p = this_p * 2; result = result * result; } if ( p == this_p ) { return result; } else { return result * Pow( x, p – this_p ); }

Version 2 object Real result = 1.0; object Real factor = x; object Real p_left = p; while ( p_left > 0 ) /*! alters result, factor, p_left maintains p_left >= 0 and result * factor ^ (p_left) = x ^ (p) decreases p_left !*/ {... }

Exercise – Write a Loop Invariant for the while loop in the following code: while (q.Length() > 1) { object Boolean left, right, combined; q.Dequeue(left); q.Dequeue(right); combined = (left != right); q.Enqueue(combined); } What does this loop do? By this, I mean, get into groups of 2-4 and write a loop invariant for the above. Assume that q is a Queue_Of_Boolean. Hint: think about how many copies of true and false will be in q after each iteration. You can use [informal descriptions] if it is helpful

Exercise (Answer) while (q.size() > 1) /*! alters q maintains [number of true values in q] mod 2 decreases |q| !*/ { object Boolean left, right, combined; q.Dequeue(left); q.Dequeue(right); combined = (left != right); q.Enqueue(combined); }

Recall Closed Lab 6 In closed lab 6, we were inputting / outputting a tree from text in a prefix notation. So, text objects like the following recorded trees in prefix notation: – a(()()) – a(b(()())c(()())) a a cb

Contract given in the Lab global_procedure Get_Tree( alters Text& tree_as_text, produces Binary_Tree_Of_Character& t ); /*! requires there exists x, y: string of character, t1: binary tree of character (tree_as_text = x * y and x = PREFIX_DISPLAY (t1)) ensures #tree_as_text = PREFIX_DISPLAY (t) * tree_as_text !*/ Notice the purpose of y is to allow there to be junk at the end of the tree as text.

Alternative Contract global_procedure Get_Tree( alters Text & tree_as_text, produces Binary_Tree_Of_Character & t ); /*! requires there exists x: string of character, t1: binary tree of character (tree_as_text = x and x = PREFIX_DISPLAY (t1)) ensures #tree_as_text = PREFIX_DISPLAY (t) * tree_as_text !*/ How does eliminating y change how this would be implemented?

Code Correctness in Lab 6 When implementing Get_Tree, it is simplest to use recursive logic. Notice what happens if we are given the tree as text: – a(b(()())c(()())) The easiest implementation would make a recursive call passing in the following text string: – b(()())c(()())) This would violate the ensures clause in the 2 nd version of the contract. The code will produce correct output, but it is not correct.

Why does this distinction matter? Perhaps this does not matter so much when implementing recursive logic, since when implementing the logic you will be embedded in both the logic of the function making the call as well as the function you are calling. When working with 2 different functions, this matters more. When you update a function, giving it a new (hopefully better) implementation, you should not need to worry about what it will do to client code that incorrectly calls it. When code works (i.e., produces correct output) but is incorrect, we have a concrete-to-concrete dependency.

Code Correctness Example 2: /*! requires ASCII(c) != 255 ensures ASCII(c) != ASCII(#c) !*/ procedure_body bar( alters Character& c ) { c++; } /*! requires ASCII(c) != 255 ensures ASCII(c) = ASCII(#c)+1 !*/ procedure_body foo( alters Character& c ) { bar(c); } Does this code work? Is it Correct?

Code Correctness Example 2: Does the code work? -- Yes. Is it correct – No. Notice that providing another correct implementation for foo would make bar fail. How could we make it correct?

Closing Remarks Thank you for listening. I have had a fun time teaching this course. Friday Closed Lab will be an Exam Review. Similar to the midterm review, I will want you to come with questions. I will not be directly preparing material. Final Exam: Monday, March 12, 11:30 AM - 1:18 PM, in DL 369 (this classroom, not the lab room). DO NOT SKIP. A passing grade on the final is required to pass the course. Are there any questions? – these only need to be relevant if there is not extra time.