735657e8933b1c5de7fd28937b4470ce.ppt
- Количество слайдов: 72
Defining Data and Functionality Peter Gorm Larsen TIVDM 1 Defining Data and Functionality 1
VDM++ Class Outline class
Agenda Ø Access Modifiers and Constructors • Instance Variables • Types • Functions • Expressions, Patterns, Bindings • Operations • Statements TIVDM 1 Defining Data and Functionality 3
Access Modifiers • VDM++ Class Members may have their access specified as public, private or protected. • The default for all members is private • Access modifiers may not be narrowed e. g. a subclass can not override a public operation in the superclass with a private operation in the subclass. • static modifiers can be used for definitions which are independent of the object state. TIVDM 1 Defining Data and Functionality 4
Constructors • Each class can have a number of constructors • Syntax identical to operations with a reference to the class name in return type • The return does not need to be made explicitly • Can be invoked when a new instance of a class gets created TIVDM 1 Defining Data and Functionality 5
A CPRNo Constructor class CPRNo instance variables date : Date; code: Digits 4; . . . operations CPRNo: Date * Patient`Sex * CPR ==> CPRNo(d, sex, cpr) == (date : = d; code : = cpr. Generate. Unique. Code(d, sex) ); end CPRNo TIVDM 1 Defining Data and Functionality 6
Agenda ü Access Modifiers and Constructors Ø Instance Variables • Types • Functions • Expressions, Patterns, Bindings • Operations • Statements TIVDM 1 Defining Data and Functionality 7
Instance Variables (1) • Used to model attributes • Consistency properties modelled as invariants class Person types string = seq of char instance variables name: string : = []; age: int : = 0; inv 0 <= age and age <= 99; end Person TIVDM 1 Defining Data and Functionality 8
Instance Variables (2) • Used to model associations • Object reference type simply written as the class name, e. g. Person • Multiplicity using VDM data types class Person. . . instance variables name: string : = []; age: int : = 0; employer: set of Company. . . end Person TIVDM 1 Defining Data and Functionality class Company. . . end Company 9
Instance Variable Access • Instance variables can only be accessed directly from within the object they belong to. • To read/write instance variables “from outside” access operations must be defined class Person. . . instance variables name: string : = []; . . . operations public Get. Name: () ==> string Get. Name () == return name end Person TIVDM 1 Defining Data and Functionality 10
Agenda ü Access Modifiers and Constructors ü Instance Variables Ø Types • Functions • Expressions, Patterns, Bindings • Operations • Statements TIVDM 1 Defining Data and Functionality 11
Type Definitions • Compound types • Basic types • Set types • Sequence types • Map types • Product types • Composite types • Union types • Optional types • Function types • Boolean • Numeric • Tokens • Characters • Quotations Invariants can be added TIVDM 1 Defining Data and Functionality 12
Boolean not b Negation bool -> bool a and b Conjunction bool * bool -> bool a or b Disjunction bool * bool -> bool a => b Implication bool * bool -> bool a <=> b Biimplication bool * bool -> bool a = b Equality bool * bool -> bool a <> b Inequality bool * bool -> bool Quantified expressions can also be considered to be basic operators but we will present them together with the other general expressions TIVDM 1 Defining Data and Functionality 13
Numeric (1) -x Unary minus real -> real abs x Absolute value real -> real floor x Floor real -> int x + y Sum real * real -> real x - y Difference real * real -> real x * y Product real * real -> real x / y Division real * real -> real x div y Integer division int * int -> int x rem y Remainder int * int -> int x mod y Modulus int * int -> int x ** y Power real * real -> real TIVDM 1 Defining Data and Functionality 14
Numeric (2) x < y Less than real * real -> bool x > y Greater than real * real -> bool x <= y Less or equal real * real -> bool x >= y Greater or equal real * real -> bool x = y Equal real * real -> bool x <> y Not equal real * real -> bool TIVDM 1 Defining Data and Functionality 15
Product and Record Types • Product type definition: A 1 * A 2 * … * An Construction of a tuple: mk_(a 1, a 2, …, an) • Record type definition: A : : selfirst : A 1 selsec : A 2 … seln : An Construction of a record: mk_A(a 1, a 2, . . . , an) TIVDM 1 Defining Data and Functionality 16
Example Record Definition A record type could be defined as: Address : : house : House. Number street : Street town : Postal. Town With field selectors: mk_Address(15, "The Grove",
Example Tuple Definition A tuple type could be defined as: nat 1 * (seq of char) * Postal. Town Then fields can be used using the. # operator: mk_(12, "Abstraction Avenue",
Invariants DT inv_DT Even = nat inv n == n mod 2 = 0 Special. Pair = nat * real – the first is smallest inv mk_(n, r) == n < r Disjoint. Sets = set of A inv ss == forall s 1, s 2 in set ss & s 1 <> s 2 => s 1 inter s 2 = {} TIVDM 1 Defining Data and Functionality 19
The Telegram Processor Sequence of letters, digits and blanks Telegram Processor Number of chargeable words and any overlength words • • Words in telegram delimited by sequence of blanks Each telegram delimited by ZZZZ Stream terminated by empty telegram (i. e. no words) Processor determines number of chargeable words in each telegram (ZZZZ and STOP are not chargeable) • Processor checks for occurrences of overlength words (more than twelve letters) • Output is neat listing of telegrams each with word count and indication of occurrence of overlength word(s) • What are the type definitions we can create here? TIVDM 1 Defining Data and Functionality 20
Data Types for Telegrams = seq of Telegram; Telegram = seq 1 of Word; Word = seq 1 of Alpha. Num inv w == w <> "ZZZZ"; Alpha. Num = Digit | Letter; Digit = char inv d == d in set {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; Letter = char inv l == l in set {'A', 'B', . . . , 'Z'} -- cheating … Reports = seq of Report; Report: : message : Telegram charge-word : nat overlength : bool TIVDM 1 Defining Data and Functionality 21
Agenda ü Access Modifiers and Constructors ü Instance Variables ü Types Ø Functions • Expressions, Patterns, Bindings • Operations • Statements TIVDM 1 Defining Data and Functionality 22
Function Definitions (1) • Explicit functions: f: A * B * … * Z -> R 1 * R 2 * … * Rn f(a, b, …, z) == expr preexpr(a, b, …, z) postexpr(a, b, …, z, RESULT) • Implicit functions: f(a: A, b: B, …, z: Z) r 1: R 1, …, rn: Rn preexpr(a, b, …, z) postexpr(a, b, …, z, r 1, …, rn) Implicit functions cannot be executed by the VDM interpreter. TIVDM 1 Defining Data and Functionality 23
Function Definitions (2) • Extended explicit functions: f(a: A, b: B, …, z: Z) r 1: R 1, …, rn: Rn == expr preexpr(a, b, …, z) postexpr(a, b, …, z, r 1, …, rn) Extended explicit functions are a non-standard combination of the implicit colon style with an explicit body. • Preliminary explicit functions: f: A * B * … * Z -> R 1 * R 2 * … * Rn f(a, b, …, z) == is not yet specified preexpr(a, b, …, z) postexpr(a, b, …, z, RESULT) TIVDM 1 Defining Data and Functionality 24
Quoting pre- and post-conditions Given an implicit function definition like: Impl. Fn(n, m: nat, pre n < m post if b then n b: bool) r: nat = r else r = m Two extra functions which can be used elsewhere automatically created: pre_Impl. Fn: nat * bool -> bool pre_Impl. Fn(n, m, b) == n < m; post_Impl. Fn: nat * bool * nat -> bool post_Impl. Fn(n, m, b, r) == if b then n = r else r = m TIVDM 1 Defining Data and Functionality 25
Example Function Definitions An implicit function definition could be: sqrt (x: nat) r: real post r * r = x and r >= 0 An explicit function definition could be: max: int * int -> int max(v 1, v 2) == if v 1 > v 2 then v 1 else v 2 TIVDM 1 Defining Data and Functionality 26
Recursive Functions and Pre-conditions A recursive function definition could look like: fac: nat 1 -> nat 1 fac (n) == if n > 1 then n * fac(n-1) else 1 Pre-conditions can also be used: Division: real * real -> real Division(p, q) == p/q pre q <> 0 TIVDM 1 Defining Data and Functionality 27
Functions for Telegram Analyse(tels : Telegrams) reps : Reports post len reps = len tels and forall i in set inds tels & reps(i) = Analyse. Tele(tels(i)); Analyse. Tele: Telegram -> Report Analyse. Tele(tel) == mk_Report(tel, Word. Count(tel), Overlength(tel)); Word. Count: Telegram -> nat Word. Count(tel) == card {j | j in set inds tel & tel(j) <> "STOP"}; Overlength: Telegram -> bool Overlength(tel) == exists w in set elems tel & len w > 12 TIVDM 1 Defining Data and Functionality 28
Agenda ü Access Modifiers and Constructors ü Instance Variables ü Types ü Functions Ø Expressions, Patterns, Bindings • Operations • Statements TIVDM 1 Defining Data and Functionality 29
Expressions • Let and let-be expressions • If-then-else expressions • Cases expressions • Quantified expressions • Set expressions • Sequence expressions • Map expressions • Tuple expressions • Record expressions • Is expressions • Define expressions • Lambda expressions TIVDM 1 Special VDM++ Expressions • New and Self expressions • Class membership expressions • Object comparison expressions • Object reference expressions Defining Data and Functionality 30
Example Let Expressions • Let expressions are used for naming complex subexpressions: let d = b ** 2 - 4 * a * c in mk_((-b – sqrt(d))/2 a, (-b + sqrt(d))/2 a) • Let expressions can also be used for breaking down complex data structures into components: let mk_Report(tel, -, ov) = rep in sub-expr TIVDM 1 Defining Data and Functionality 31
Example Let-be expressions • Let-be-such-that expressions are even more powerful. A free choice can be expressed: let i in set inds l be st Largest(elems l, l(i)) in sub_expr and let l in set Permutations(list) be st forall i, j in set inds l & i < j => l(i) <= l(j) in l TIVDM 1 Defining Data and Functionality 32
If-then-else Expressions If-then-else expressions are similar to those known from programming languages. if c then else in set dom rq rq(c) {} and if i = 0 then
Cases Expressions Cases expressions are very powerful because of pattern matching: cases com: mk_Loan(a, b) -> mk_Receive(a, b) mk_Status(l) -> others -> ”some end a^” has borrowed “^b, -> a^” has returned “^b, l^” are borrowing “^Borrows(l), other command is used” and cases a: mk_A(a’, -, a’) -> Expr(a’), mk_A(b, b, c) -> Expr 2(b, c) end TIVDM 1 Defining Data and Functionality 34
Set Expressions • Set enumeration: {a, 3, 3, true} • Set comprehension can either use set binding: {a+2 | mk_(a, a) in set {mk_(true, 1), mk_(1, 1)}} or type binding: {a | a: nat & a<10} • Set range expression: {3, . . . , 10} TIVDM 1 Defining Data and Functionality 35
Sequence Expressions • Sequence enumeration: [7. 7, true, ”I”, true] • Sequence comprehension can only use a set bind with numeric values (numeric order is used): [i*i | i in set {1, 2, 4, 6}] and [i | i in set {6, 3, 2, 7} & i mod 2 = 0] • Subsequence expression: [4, true, ”string”, 9, 4](2, . . . , 4) TIVDM 1 Defining Data and Functionality 36
Map Expressions • Map enumeration: {1|->true, 7|->6} • Map comprehension can either use type binding: {i|->mk_(i, true) | i: bool} or set binding: {a+b|->b-a | a in set {1, 2}, b in set {3, 6}} and {i|->i | i in set {1, . . . , 10} & i mod 3 = 0} One must be careful to ensure that every domain element maps uniquely to one range element. TIVDM 1 Defining Data and Functionality 37
Tuple Expressions • A tuple expression looks like: mk_(2, 7, true, {|->}) • Remember that tuple values from a tuple type will always • have the same length and • use the same types (possible union types) at corresponding positions. • On the other hand the length of a sequence value may vary but the elements of the sequence will always be of the same type. TIVDM 1 Defining Data and Functionality 38
Record Expression Given two type definitions like: A : : n: b: s: B : : n: r: nat bool set of nat; nat real one can write expressions like: mk_A(1, true, {8}) mk_B(3, 3) mu (mk_A(7, false, {1, 4}), n|->1, s|->{}) mu (mk_B(3, 4), r|->5. 5) The mu operator is called “the record modifier”. TIVDM 1 Defining Data and Functionality 39
Apply Expressions • Map applications: let m = {true|->5, 6|->{}} in m(true) • Sequence applications: [2, 7, true](2) • Field select expressions: let r = mk_A(2, false, {6, 9}) in r. b TIVDM 1 Defining Data and Functionality 40
Is Expressions Basic values and record values can be tested by is- expressions. is_nat(5) will yield true. is_C(mk_C(5)) will also yield true, given that C is defined as a record type having one component which 5 belongs to. is_A(mk_B(3, 7)) is_A(6) TIVDM 1 will always yield false. will also always yield false. Defining Data and Functionality 41
Define Expressions The right-hand side of a define expression has access to the instance variables. The state could be changed by an operation call: def a = Op. Call(arg 1, arg 2) in f(a) or parts of the state could simply be read: def a = instance_variable in g(a) TIVDM 1 Defining Data and Functionality 42
Lambda Expressions • Lambda expressions are an alternative way of defining explicit functions. lambda n: nat & n * n • They can take a type bind list: lambda a: nat, b: bool & if b then a else 0 • or use more complex types: lambda mk_(a, b): nat * nat & a + b TIVDM 1 Defining Data and Functionality 43
New and Self Expressions • The new expression creates an instance of a class and yields a reference to it. • Given a class called C this will create an instance of C and return its reference: new C() • The self expression yields the reference of an object. • Given a class with instance variable a of type nat this will initialize an object and yield its reference: Create: nat ==> C Create (n) == ( a : = n; return self ) TIVDM 1 Defining Data and Functionality 44
Class Membership Expressions Check if an object is of a particular class. isofclass(Class_name, object_ref) Returns true if object_ref is of class Class_name or a subclass of Class_name. Check for the baseclass of a given object. isofbaseclass(Class_name, object_ref) For the result to be true, object_ref must be of class Class_name, and Class_name cannot have any superclasses. TIVDM 1 Defining Data and Functionality 45
Examples Temporary Employee Secretary Manager If s: Secretary and m: Manager r r isofclass(Employee, m) true r isofclass(Manager, s) false r isofbaseclass(Employee, m) true r isofbaseclass(Secretary, s) false r TIVDM 1 isofclass(Secretary, s) isofbaseclass(Temporary, s) true Defining Data and Functionality true 46
Object Comparison Expressions Compare two objects. sameclass(obj 1, obj 2) True if and only if obj 1 and obj 2 are instances of the same class r sameclass(m, s) false r sameclass(m, new Manager()) true Comparison of baseclasses of two objects. samebaseclass(obj 1, obj 2) r samebaseclass(m, s) true r samebaseclass(m, new Temporary()) false TIVDM 1 Defining Data and Functionality 47
Object Reference Expressions • The = and <> operators perform comparison of object references. • = will only yield true, if the two objects are in fact the same instance. • <> will yield true, if the two objects are not the same instance, even if they have the same values in all instance variables. TIVDM 1 Defining Data and Functionality 48
Patterns and Pattern Matching • Patterns are empty shells • Patterns are matched thereby binding the pattern identifiers • There are special patterns for • • Basic values Pattern identifiers Don’t care patterns Sets Sequences Tuples Records but not for maps TIVDM 1 Defining Data and Functionality 49
Bindings • A binding matches a pattern to a value. • A set binding: pat in set expr where expr must denote a set expression. pat is bound to the elements of the set expr • A type binding: pat : type Here pat is bound to the elements of type. Type bindings cannot be executed by the interpreter, because such types can be infinitely large. TIVDM 1 Defining Data and Functionality 50
Agenda ü Access Modifiers and Constructors ü Instance Variables ü Types ü Functions ü Expressions, Patterns, Bindings Ø Operations • Statements TIVDM 1 Defining Data and Functionality 51
Operation Definitions (1) • Explicit operation definitions: o: A * B *. . . ==> R o(a, b, . . . ) == stmt pre expr post expr • Implicit operations definitions: o(a: A, b: B, . . . ) r: R ext rd. . . wr. . . pre expr post expr TIVDM 1 Defining Data and Functionality 52
Operation Definitions (2) • Preliminary operation definitions: o: A * B *. . . ==> R o(a, b, . . . ) == is not yet specified pre expr post expr • Delegated operation definitions: o: A * B *. . . ==> R o(a, b, . . . ) == is subclass responsibility pre expr post expr TIVDM 1 Defining Data and Functionality 53
Operation Definitions (3) • Operations in VDM++ can be overloaded • Different definitions of operations with same name • Argument types must not be overlapping statically (structural equivalence omitting invariants) TIVDM 1 Defining Data and Functionality 54
Example Operation Definitions An implicit operation definition could look like: Withdraw(amount: nat) new. Balance: int ext rd limit : int wr balance : int pre balance - amount > limit post balance + amount = balance~ and new. Balance = balance An explicit operation definition could look like: Withdraw: nat ==> int Withdraw(amount) == ( balance : = balance - amount; return balance ) pre balance - amount > limit TIVDM 1 Defining Data and Functionality 55
Agenda ü Access Modifiers and Constructors ü Instance Variables ü Types ü Functions ü Expressions, Patterns, Bindings ü Operations Ø Statements TIVDM 1 Defining Data and Functionality 56
Statements • Let and Let-be statements • Define Statements • Block statements • Assign statements • Conditional statements • For loop statements • While loop statements • Call Statements TIVDM 1 • Non deterministic statements • Return statements • Exception handling statements • Error statements • Identity statements Defining Data and Functionality 57
Let and Let-be Statements Let statements are used for naming complicated constructs and for decomposing complex structures let cs’ = {c |-> cs(c) union {s}}, ct’ = {s |-> ct(s) union {c}} in sub_stmt 1 Let-be-such-that statements are even more powerful. A free choice can be expressed: let i in set inds l be st Largest (elems l, l(i)) in sub_stmt 2 and let l in set Permutations(list) be forall i, j in set inds l & i < in return l TIVDM 1 Defining Data and Functionality st j => l(i) <= l(j) 58
Define Statements • Allows binding of the result of an operation call to a pattern: def mk_(r, -) = Op. Call() in (x : = r / 2; return x) TIVDM 1 Defining Data and Functionality 59
Block Statements • The block statement corresponds to block statements from traditional high-level programming languages. • It can contain local variables, which must be typed and can be initialised. • (dcl a: nat : = 5; dcl b: bool; stmt 1; stmt 2; . . . stmtn) • If stmt 1 returns a value the execution of the block is terminated and this value is returned as the result of the entire block. TIVDM 1 Defining Data and Functionality 60
Assign Statements • The assign statement is a generalisation of assignment statements from traditional high-level programming languages. It is used to change the value of a global or local state. • Assume that x is a global or local state component of type nat, then it can be assigned a value: x : = 5 • More complex assignments exists. Assume x is of record type with a field s which is a map: x. s(3) : = true TIVDM 1 Defining Data and Functionality 61
If-then-else Statements If-then-else statements are similar to those known from programming languages. if c in set dom rq then reqs : = rq(c) else return {} and if i = 0 then return elseif 1 <= then return else return
Cases Statements Cases statements are very powerful because of pattern matching: cases com: mk_Loan(a, b) -> return a^” has borrowed “^b, mk_Receive(a, b) -> return a^” has returned “^b, mk_Status(l) -> return l^” are borrowing “^Borrows(l), others -> return ”some other command is used” end and cases a: mk_A(a’, -, a’) -> Expr(a’), mk_A(b. b. c) -> Expr 2(b, c) end Notice that the bodies of the alternatives are statements. TIVDM 1 Defining Data and Functionality 63
For Loop Statements • Index for loop statement: for id = lower to upper by step do stmt • Set for loop statement: for all pat in setexpr do stmt • Sequence for loop statement: for pat in seqexpr do stmt TIVDM 1 Defining Data and Functionality 64
While Loop Statements • While loop statement: while expr do stmt • expr is recalculated at the termination of each evaluation of the body statement stmt. TIVDM 1 Defining Data and Functionality 65
Nondeterministic Statement • A nondeterministic statement contains a sequence of statements that are executed in arbitrary order. || (stmt 1, stmt 2, . . . , stmtn) TIVDM 1 Defining Data and Functionality 66
Return Statements The return statement returns the value of an expression inside an operation: return expr or simply return Note that if a value is returned by either a call statement or a return statement the execution of the operation is terminated. Thus, succeeding statements will not be executed. TIVDM 1 Defining Data and Functionality 67
Exception Handling Statements • The exit statement raises an exception: exit expr is optional. • Always statement: (dcl mem: Memory; always Free(mem) in (mem : = Allocate(); Command(mem, . . . ))) TIVDM 1 Defining Data and Functionality 68
Exception Handling Statements • Trap statement: trap pat with Error. Action(pat) in (dcl mem: Memory; always Free(mem) in (mem : = Allocate(); Command(mem, . . . ))) • Recursive trap statement: tixe {(
Error and Identity Statements • The error statement states that the result of a statement is undefined and therefore an error has occurred. if a =
Summary • What have I presented today? • • • Access Modifiers and Constructors Instance Variables Types Functions Expressions, Patterns, Bindings Operations and Statements • What do you need to do now? • Continue with your project • Present your status to all of us • Read chapter 6 before next lecture TIVDM 1 Defining Data and Functionality 71
Quote of the day • Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning. By Rick Cook TIVDM 1 Defining Data and Functionality 72


