CS195, Class 22: Using Assertions Overview: * Two uses for assertions * Some notation * Assertions about assignments * Assertions about sorting Notes: * Forgot book. Talk. Free Lunch => No outline. Weak prep. Sorry. * How are the time requirements going? * Anything puzzling? ---------------------------------------- What did Gries say in Chapter 6. * You can use assertions to establish pre and postconditions for functions. * We can then prove programs correct. * Need to show that when preconditions are met, your postconditions will hold. * You can also use preconditions and postconditions to define operations. { x = X; y = Y; } swap(x,y) { x = Y; y = X; } * Some folks use this style to define the meaning of programming languages + That's what Gries will do. How can we use preconditions and postconditions to specify the meaning of x := y; { x = X; y = Y; } swap(x,y) { x = Y; y = Y; } [See the real whiteboard for details.] { array(x) x = X } y := sort(x) { x = X array(y) permutation(x,y) For i = 0 to n-2 y[i] <= y[i+1] } Implementation of sort: x := [1,2] y := [1,2] Backwards Consider x := y; If the postcondition is simply { x = y } The implementation can be Shove 0 into x; shove 0 into y ---------------------------------------- { array(x) x = X } sort!(x) { permutation(x,X) For i = 0 to n-2 x[i] <= x[i+1] } ---------------------------------------- How can we formally define permutation? { } permuation(x,y) { } ---------------------------------------- (define permutation? (lambda (x y) )) public boolean permutationP(int[] x, int[] y) { for (int i = 0; i < x.length; i++) if (y does not contain x[i]) return false; return true; } // permutationP(int[], int[]) This will return true for x=[1,2,2] and y=[1,1,2] Pick some element, v COunt the number of times v occurs in x Count the number of times v occurs in y If the two counts are different, return false Otherwise ... (define permutation? (lambda (x y) (or (and (null? x) (null? y)) (and (member (car x) y) (permutation? (cdr x) (remove-one-copy (car x) y)))))) We'll need to use loops. { x = X y = Y } permutation(x,y) { x = X y = Y exists p (an array) for all i from 0 to n-1 x[i] = y[p[i]] for all j,k from 0 to n-1, j!=k p[j] != p[k]