Abstraction Functions and Representation Invariants

Similar documents
Balanced Trees. Prof. Clarkson Fall Today s music: Get the Balance Right by Depeche Mode

Abstraction and Specification

Modules and Representation Invariants

Balanced Trees. Nate Foster Spring 2018

Testing. Prof. Clarkson Fall Today s music: Wrecking Ball by Miley Cyrus

Lists. Prof. Clarkson Fall Today s music: "Blank Space" by Taylor Swift

Modular Programming. Prof. Clarkson Fall Today s music: "Giorgio By Moroder" by Daft Punk

CS3110 Spring 2016 Lecture 6: Modules

CS 11 Ocaml track: lecture 4. Today: modules

CIS 120 Midterm I October 2, Name (printed): Username (login id):

Programming Languages and Techniques (CIS120)

Assertions, pre/postconditions

CS Lecture 14: Hash tables. Prof. Clarkson Spring Today s music: Re-hash by Gorillaz

Futures. Prof. Clarkson Fall Today s music: It's Gonna be Me by *NSYNC

CS Prof. Clarkson Fall 2014

Specifications. Prof. Clarkson Fall Today s music: Nice to know you by Incubus

Async. Prof. Clarkson Fall Today s music: It's Gonna be Me by *NSYNC

Programming Languages and Techniques (CIS120)

Some Advanced ML Features

Interpreters. Prof. Clarkson Fall Today s music: Step by Step by New Kids on the Block

Behavioral Equivalence

Representation Invariants and Abstraction Functions

Representation Invariant, Abstraction Function

Behavioral Equivalence

Amortized Analysis. Prof. Clarkson Fall Today s music: : "Money, Money, Money" by ABBA

Hash Tables. Nate Foster Spring 2018

Verification in Coq. Prof. Clarkson Fall Today s music: Check Yo Self by Ice Cube

Assertions. Assertions - Example

n Specifying what each method does q Specify it in a comment before method's header n Precondition q Caller obligation n Postcondition

CS Lecture 5: Pattern Matching. Prof. Clarkson Fall Today s music: Puff, the Magic Dragon by Peter, Paul & Mary

CS 1110: Introduction to Computing Using Python Loop Invariants

Programming Languages and Techniques (CIS120)

Refresher: Interface Specifications. ADT Documentation. Set Represented as an Array. Representation Invariant, Abstraction Function

Lecture 31: Graph Search & Game 10:00 AM, Nov 16, 2018

Monads. Prof. Clarkson Fall Today s music: Vámanos Pal Monte by Eddie Palmieri

The Design Recipe Fall 2018

CSE 130, Fall 2005: Final Examination

Programming Languages. Example 5. Example 4. CSE 130 : Fall type, can reuse code for all types! let rec cat l = match l with

CS Lecture 19: Loop invariants

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

CMSC 330: Organization of Programming Languages. OCaml Expressions and Functions

Midterm 2. CMSC 430 Introduction to Compilers Fall Instructions Total 100. Name: November 11, 2015

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003

Two approaches to writing interfaces

Suppose that the following is from a correct C++ program:

Lecture 7 Abstraction Functions

CS 315 Software Design Homework 3 Preconditions, Postconditions, Invariants Due: Sept. 29, 11:30 PM

CSE 130, Fall 2006: Final Examination

Programming Languages and Techniques (CIS120)

CIS 120 Midterm II March 29, 2013 SOLUTIONS

CS 321 Programming Languages

CMSC 330: Organization of Programming Languages

References: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 10/14/2004 1

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples

Testing and Debugging

CMSC 330: Organization of Programming Languages. Formal Semantics of a Prog. Lang. Specifying Syntax, Semantics

CIS 120 Midterm I February 16, 2015 SOLUTIONS

The Design Recipe Fall 2017

CMSC 330 Exam #2 Fall 2008

Proofs are Programs. Prof. Clarkson Fall Today s music: Proof by Paul Simon

Programming Languages and Techniques (CIS120e)

CS 1110 Final Exam Solutions May 2018

Mutable Data Types. Prof. Clarkson Fall A New Despair Mutability Strikes Back Return of Imperative Programming

Map and Fold. Prof. Clarkson Fall Today s music: Selections from the soundtrack to 2001: A Space Odyssey

EPITA - Practical Programming 06 - Advanced Module Usage

Readability [Skrien 4.0] Programs must be written for people to read, and only incidentally for machines to execute.

CS3110 Spring 2017 Lecture 10 a Module for Rational Numbers

Programming Languages and Techniques (CIS120)

CS Lecture 6: Map and Fold. Prof. Clarkson Fall Today s music: Selections from the soundtrack to 2001: A Space Odyssey

Lecture 5 Representation Invariants

Introduction to OCaml

OCaml Language Choices CMSC 330: Organization of Programming Languages

CS558 Programming Languages

CS21: INTRODUCTION TO COMPUTER SCIENCE. Prof. Mathieson Fall 2017 Swarthmore College

SEARCHING AND SORTING HINT AT ASYMPTOTIC COMPLEXITY

CS 11 Ocaml track: lecture 2

Balanced Trees. Nate Foster Spring 2019

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

Proofs are Programs. Prof. Clarkson Fall Today s music: Two Sides to Every Story by Dyan Cannon and Willie Nelson

Solutions to Quiz 1 (March 14, 2016)

Introduction to Prof. Clarkson Fall Today s music: Prelude from Final Fantasy VII by Nobuo Uematsu (remastered by Sean Schafianski)

CSE 331 Final Exam 3/16/15 Sample Solution

CS558 Programming Languages

Representation invariants and abstraction functions CSE 331 UW CSE

CPS122 Lecture: Detailed Design and Implementation

Reference Cells. Example

(Provisional) Lecture 32: Estimated Value, Minimax, Functional Data 10:00 AM, Nov 20, 2017

CMSC 330, Fall 2013, Practice Problems 3

EECS 183. Week 3 - Diana Gage. www-personal.umich.edu/ ~drgage

Note that this is a rep invariant! The type system doesn t enforce this but you need it to be true. Should use repok to check in debug version.

CSCI-GA Scripting Languages

CS558 Programming Languages

Solutions to Quiz 1 (March 22, 2019)

Programming Languages and Techniques (CIS120)

Harvard School of Engineering and Applied Sciences CS 152: Programming Languages

Lists. Michael P. Fourman. February 2, 2010

Forward recursion. CS 321 Programming Languages. Functions calls and the stack. Functions calls and the stack

Formal Semantics. Prof. Clarkson Fall Today s music: Down to Earth by Peter Gabriel from the WALL-E soundtrack

CS 370 The Pseudocode Programming Process D R. M I C H A E L J. R E A L E F A L L

CS251 Programming Languages Handout # 29 Prof. Lyn Turbak March 7, 2007 Wellesley College

Transcription:

Abstraction Functions and Representation Invariants Prof. Clarkson Fall 2017 Today s music: In C by Terry Riley

A2 Implement a text adventure game engine, and write your own adventure Experience with lists, trees, records, modules Start early! My solution about 400 LoC (beyond release code, excluding comments) Nearly all the design is up to you

Review Previously in 3110: Abstraction and specification Specifying functions Today: Specifying data abstractions Representation types Abstraction functions Representation invariants

Where to write specifications Put specs where clients will find them In signature Usually in.mli file Not where implementer will write code In structure Usually in.ml file And don t duplicate them between.ml and.mli!

Back to: Audience of specification Clients Spec informs what they must guarantee (preconditions) Spec informs what they can assume (postconditions) Implementers Spec informs what they can assume (preconditions) Spec informs what they must guarantee (postconditions) But the spec isn t enough for implementers...

REPRESENTATION TYPES

Example: sets module type Set = sig type 'a t val empty : 'a t val mem : 'a -> 'a t-> bool val add : 'a -> 'a t-> 'a t val size : 'a t-> int end

Sets without duplicates module ListSetNoDup : Set = struct (* the list may never have duplicates *) type 'a t = 'a list let empty = [] let mem = List.mem let add x l = if mem x l then l else x :: l let size = List.length end

Sets with duplicates module ListSetDup : Set = struct (* the list may have duplicates *) end type 'a t = 'a list let empty = [] let mem = List.mem let add x l = x :: l let rec size = function [] -> 0 h::t -> size t + (if mem h t then 0 else 1 )

Compare set implementations Both have the same representation type, 'a list But they interpret values of that type differently [1;1;2] is {1,2} in ListSetDup [1;1;2] is not meaningful in ListSetNoDup In both, [1;2] and [2;1] are {1,2} Interpretation differs because they make different assumptions about what values of that type can be: passed into operations returned from operations e.g., [1;1;2] can be passed into and returned from ListSetDup [1;1;2] should not be passed into or returned from ListSetNoDup

Question Consider this implementation of set union with representation type 'a list: let union l1 l2 = l1 @ l2 Under which invariant on representation type will that implementation be correct? A. There may be duplicates in lists B. There may not be duplicates in lists C. Both A and B D. Neither A nor B

Question Consider this implementation of set union with representation type 'a list: let union l1 l2 = l1 @ l2 Under which invariant on representation type will that implementation be correct? A. There may be duplicates in lists B. There may not be duplicates in lists C. Both A and B D. Neither A nor B

Representation type questions Q: How to interpret the representation type as the data abstraction? A: Abstraction function Q: How to determine which values of representation type are meaningful? A: Representation invariant

Abstraction function Abstraction function (AF) captures designer s intent in choosing a particular representation of a data abstraction Not actually an OCaml function, but a mathematical function Maps concrete values to abstract values client s view {1,2} {7} abstract: set abstraction barrier implementer s view [1;2] [2;1] [7] concrete: lists (no dups)

AF properties Many-to-one: many values of concrete type can map to same value of abstract type [1;2] maps to {1,2}, as does [2;1] Partial: some values of concrete type do not map to any value of abstract type [1;1;2] (in no dups) does not map to any set

Documenting AFs module ListSetNoDup : Set = struct (* AF: the list [a1;...; an] represents * the set {a1,...,an}. [] represents * the empty set. *) type 'a t = 'a list... end module ListSetDup : Set = struct (* AF: the list [a1;...; an] represents * the smallest set containing the * elements a1,..., an. [] represents * the empty set. *) type 'a t = 'a list... end

Documenting AFs You might write: (* Abstraction Function: comment *) (* AF: comment *) You write it FIRST It s the number one decision you have to make while implementing a data abstraction It gives meaning to representation It dictates what values are necessary in a module, or what fields are necessary in an object, or what

Implementing AFs Mostly you don t Would need to have an OCaml type for abstract values If you had that type, you d already be done... But sometimes you do something similar: string_of_x or to_string or format quite useful for debugging

Duplicates? module ListSetNoDup : Set = struct (* AF: the list [a1;...; an] represents * the set {a1,...,an}. [] represents * the empty set. *) type 'a t = 'a list... end module ListSetDup : Set = struct (* AF: the list [a1;...; an] represents * the smallest set containing the * elements a1,..., an. [] represents * the empty set. *) type 'a t = 'a list... end So far, nothing other than name of module specifies whether duplicates are allowed

Representation invariant Representation invariant characterizes which concrete values are valid and which are invalid Rep invariant or "RI" for short Valid concrete values mapped by AF to abstract values Invalid concrete value not mapped by AF to any abstract values Closely related to class invariants that you saw in 2110 RI is a fact whose truth is invariant except for limited blocks of code (much like loop invariants from 2110) RI is implicitly part of pre- and post-conditions operations may violate it temporarily (e.g., construct a list with duplicates then throw out the duplicates)

Representation invariant concrete input concrete operation concrete output RI holds RI maybe violated RI holds

Documenting RI module ListSetNoDup : Set = struct (* AF: the list [a1;...; an] represents * the set {a1,...,an}. [] represents * the empty set. *) (* RI: the list contains no duplicates *) type 'a t = 'a list end module ListSetDup : Set = struct (* AF: the list [a1;...; an] represents * the smallest set containing the * elements a1,..., an. [] represents * the empty set. * RI: none *) type 'a t = 'a list end

Implementing the RI Implement it early, before any operations are implemented Common idiom: if RI fails then raise exception, otherwise return concrete value let rep_ok (x:'a list) : 'a list = if has_dups x then failwith "RI" else x When debugging, check rep_ok on every input to an operation and on every output...

Checking the RI module ListSetNoDup : Set = struct (* AF:... *) (* RI:... *) type 'a t = 'a list let rep_ok =... let empty = rep_ok [] let mem x l = List.mem x (rep_ok l) let add x l = let l' = rep_ok l in if mem x l' then l' else rep_ok(x :: l') let size l = List.length (rep_ok l) end Funny story...this saved a CS 3110 tournament one year

Checking the RI Can be expensive! For production code, options include... only check cheap parts of RI comment out "real" implementation, change rep_ok to identity function, let compiler optimize call away use language features for condition compilation (in OCaml, CamlP4 or PPX)

CORRECTNESS OF OPERATIONS

AF and operations {1,2} union {2,3} abstract operation {1,2;3} AF Example: ListSetDup AF [1;2] concrete operation append [2;3] [1;2;2;3]

AF and operations abstract operation AF AF implemented operation commutative diagram: both paths lead to the same place

Correctness of operations Implementation is correct if AF commutes: op abs (AF(c)) = AF(op conc (c)) c is a concrete value for which RI holds op conc is the concrete implementation of the operation, e.g. list append op abs is the abstract operation (not implemented), e.g. set union

Recap: Specifying rep. types Q: How to interpret the representation type as the data abstraction? A: Abstraction function Q: How to determine which values of representation type are meaningful? A: Representation invariant

Upcoming events N/A This is invariant. THIS IS 3110