Advanced Recursion Design by Contract Data Abstraction - PowerPoint PPT Presentation

About This Presentation
Title:

Advanced Recursion Design by Contract Data Abstraction

Description:

2. Recursive call to Fact. 4. Unfinished Business. 3. Create a new Stack Frame ... Call the function: answer - Fact(5) Main Algorithm: Unfinished: answer - Fact (5) ... – PowerPoint PPT presentation

Number of Views:38
Avg rating:3.0/5.0
Slides: 87
Provided by: jona168
Category:

less

Transcript and Presenter's Notes

Title: Advanced Recursion Design by Contract Data Abstraction


1
Advanced RecursionDesign by ContractData
Abstraction
Lecture 7
2
Advanced Recursion
3
Recursive Function Example Factorial
  • Problem calculate n! (n factorial)
  • n! 1 if n 0
  • n! 1 2 3 ... n if n gt 0
  • Recursively
  • if n 0, then n! 1
  • if n gt 0, then n! n (n-1)!

4
Solving Recursive Problems
  • See recursive solutions as two sections
  • Current
  • Rest
  • N! N (N-1)!
  • 7! 7 6!
  • 7! 7 (6 5 4 3 2 1 1)

5
Factorial Function
  • function Factorial returnsa Num
  • (n isoftype in Num)
  • // Calculates n factorial, n!
  • // Precondition n is a non-negative
  • // integer
  • if (n 0) then
  • Factorial returns 1
  • else
  • Factorial returns n Factorial(n-1)
  • endif
  • endfunction //Factorial

6
if (0 0) then Fact returns 1 else
Fact returns 1 endif endfunction //Fact
if (1 0) then Fact returns 1 else
Fact returns 1 Fact(0) endif endfunction //Fact
if (2 0) then Fact returns 1 else
Fact returns 2 Fact(1) endif endfunction //Fact
if (3 0) then Fact returns 1 else
Fact returns 3 Fact(2) endif endfunction //Fact
algorithm Test ans lt- Fact(3) endalgorithm
7
Tracing Details
function Fact returnsa Num (2) if (2 0)
then Fact returns 1 else Fact returns 2
Fact(1) endif endfunction //Fact
8
Activation Stack for Factorial
  • Call the function answer lt- Fact(5)

Main Algorithm Unfinished answer lt- Fact (5)
9
Activation Stack for Factorial
Fact. 1st N5, Unfinished
5Fact(4)
Main Algorithm Unfinished answer lt- Fact (5)
10
Activation Stack for Factorial
Fact. 2nd N4, Unfinished
4Fact(3)
Fact. 1st N5, Unfinished
5Fact(4)
Main Algorithm Unfinished answer lt- Fact (5)
11
Activation Stack for Factorial
Fact. 3rd N3, Unfinished
3Fact(2)
Fact. 2nd N4, Unfinished
4Fact(3)
Fact. 1st N5, Unfinished
5Fact(4)
Main Algorithm Unfinished answer lt- Fact (5)
12
Activation Stack for Factorial
Fact. 4th N2, Unfinished
2Fact(1)
Fact. 3rd N3, Unfinished
3Fact(2)
Fact. 2nd N4, Unfinished
4Fact(3)
Fact. 1st N5, Unfinished
5Fact(4)
Main Algorithm Unfinished answer lt- Fact (5)
13
Activation Stack for Factorial
Fact. 5th N1, Unfinished
1Fact(0)
Fact. 4th N2, Unfinished
2Fact(1)
Fact. 3rd N3, Unfinished
3Fact(2)
Fact. 2nd N4, Unfinished
4Fact(3)
Fact. 1st N5, Unfinished
5Fact(4)
Main Algorithm Unfinished answer lt- Fact (5)
14
Activation Stack for Factorial
Fact. 6th N0, Finished
returns 1
Fact. 5th N1, Unfinished
1Fact(0)
Fact. 4th N2, Unfinished
2Fact(1)
Fact. 3rd N3, Unfinished
3Fact(2)
Fact. 2nd N4, Unfinished
4Fact(3)
Fact. 1st N5, Unfinished
5Fact(4)
Main Algorithm Unfinished answer lt- Fact (5)
15
Activation Stack for Factorial
Fact. 5th N1, Finished
returns 11
Fact. 4th N2, Unfinished
2Fact(1)
Fact. 3rd N3, Unfinished
3Fact(2)
Fact. 2nd N4, Unfinished
4Fact(3)
Fact. 1st N5, Unfinished
5Fact(4)
Main Algorithm Unfinished answer lt- Fact (5)
16
Activation Stack for Factorial
Fact. 4th N2, Finished returns 21
Fact. 3rd N3, Unfinished
3Fact(2)
Fact. 2nd N4, Unfinished
4Fact(3)
Fact. 1st N5, Unfinished
5Fact(4)
Main Algorithm Unfinished answer lt- Fact (5)
17
Activation Stack for Factorial
Fact. 3rd N3, Finished
returns 32
Fact. 2nd N4, Unfinished
4Fact(3)
Fact. 1st N5, Unfinished
5Fact(4)
Main Algorithm Unfinished answer lt- Fact (5)
18
Activation Stack for Factorial
Fact. 2nd N4, Finished
returns 46
Fact. 1st N5, Unfinished
5Fact(4)
Main Algorithm Unfinished answer lt- Fact (5)
19
Activation Stack for Factorial
Fact. 1st N5, Finished
returns 524
Main Algorithm Unfinished answer lt- Fact (5)
20
Activation Stack for Factorial
Main Algorithm Finished answer lt- 120
21
Exponentiation
LB
  • baseexponent
  • e.g. 53
  • Could be written as a function
  • Power(base, exp)

22
Can we write it recursively?
LB
  • be b b(e-1)
  • Whats the limiting case?
  • When e 0 we have b0 which always equals?
  • 1

23
Another Recursive Function
  • function Power returnsa Num
  • (base, exp isoftype in Num)
  • // Computes the value of BaseExp
  • // Pre exp is a non-negative integer
  • if (exp 0) then
  • Power returns 1
  • else
  • Power returns base Power(base, exp-1)
  • endif
  • endfunction //Power

24
Activations Stack Example
Function Power returnsa Num (base, exp isoftype
in Num) //Computes the value of
BaseExp //Preconditions exp is a non-negative
integer if(exp 0 ) then Power returns 1
else Power returns (base
Power(base, exp 1)) endif endfunction //Power
1
3
9
27
Total lt- 81
25
Bunnies?
LB
  • The Time 13th Century
  • The Place Italy
  • The Man Fibonacci
  • The Problem We start with a pair of newborn
    rabbits. At the end of the 2nd month, and each
    month thereafter the female gives birth to a new
    pair of rabbits one male and one female. The
    babies mature at the same rate as the parents and
    begin to produce offspring on the same schedule.
    So how many rabbits do we have at the end of one
    year?

26
LB
27
A More Complex Recursive Function
  • Fibonacci Number Sequence
  • if n 1, then Fib(n) 1
  • if n 2, then Fib(n) 1
  • if n gt 2, then Fib(n) Fib(n-2) Fib(n-1)
  • Numbers in the series
  • 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

28
Fibonacci Sequence Function
  • function Fib returnsa Num (n iot in Num)
  • // Calculates the nth Fibonacci number
  • // Precondition N is a positive integer
  • if ((n 1) OR (n 2)) then
  • Fib returns 1
  • else
  • Fib returns Fib(n-2) Fib(n-1)
  • endif
  • endfunction //Fibonacci

29
Tracing with Multiple Recursive Calls
Main Algorithm answer lt- Fib(5)
30
Tracing with Multiple Recursive Calls
Fib(5) Fib returns Fib(3) Fib(4)
Main Algorithm answer lt- Fib(5)
31
Tracing with Multiple Recursive Calls
Fib(3) Fib returns Fib(1) Fib(2)
Fib(5) Fib returns Fib(3) Fib(4)
Main Algorithm answer lt- Fib(5)
32
Tracing with Multiple Recursive Calls
Fib(1) Fib returns 1
Fib(3) Fib returns Fib(1) Fib(2)
Fib(5) Fib returns Fib(3) Fib(4)
Main Algorithm answer lt- Fib(5)
33
Tracing with Multiple Recursive Calls
Fib(3) Fib returns 1 Fib(2)
Fib(5) Fib returns Fib(3) Fib(4)
Main Algorithm answer lt- Fib(5)
34
Tracing with Multiple Recursive Calls
Fib(2) Fib returns 1
Fib(3) Fib returns 1 Fib(2)
Fib(5) Fib returns Fib(3) Fib(4)
Main Algorithm answer lt- Fib(5)
35
Tracing with Multiple Recursive Calls
Fib(3) Fib returns 1 1
Fib(5) Fib returns Fib(3) Fib(4)
Main Algorithm answer lt- Fib(5)
36
Tracing with Multiple Recursive Calls
Fib(5) Fib returns 2 Fib(4)
Main Algorithm answer lt- Fib(5)
37
Tracing with Multiple Recursive Calls
Fib(4) Fib returns Fib(2) Fib(3)
Fib(5) Fib returns 2 Fib(4)
Main Algorithm answer lt- Fib(5)
38
Tracing with Multiple Recursive Calls
Fib(2) Fib returns 1
Fib(4) Fib returns Fib(2) Fib(3)
Fib(5) Fib returns 2 Fib(4)
Main Algorithm answer lt- Fib(5)
39
Tracing with Multiple Recursive Calls
Fib(4) Fib returns 1 Fib(3)
Fib(5) Fib returns 2 Fib(4)
Main Algorithm answer lt- Fib(5)
40
Tracing with Multiple Recursive Calls
Fib(3) Fib returns Fib(1) Fib(2)
Fib(4) Fib returns 1 Fib(3)
Fib(5) Fib returns 2 Fib(4)
Main Algorithm answer lt- Fib(5)
41
Tracing with Multiple Recursive Calls
Fib(1) Fib returns 1
Fib(3) Fib returns Fib(1) Fib(2)
Fib(4) Fib returns 1 Fib(3)
Fib(5) Fib returns 2 Fib(4)
Main Algorithm answer lt- Fib(5)
42
Tracing with Multiple Recursive Calls
Fib(3) Fib returns 1 Fib(2)
Fib(4) Fib returns 1 Fib(3)
Fib(5) Fib returns 2 Fib(4)
Main Algorithm answer lt- Fib(5)
43
Tracing with Multiple Recursive Calls
Fib(2) Fib returns 1
Fib(3) Fib returns 1 Fib(2)
Fib(4) Fib returns 1 Fib(3)
Fib(5) Fib returns 2 Fib(4)
Main Algorithm answer lt- Fib(5)
44
Tracing with Multiple Recursive Calls
Fib(3) Fib returns 1 1
Fib(4) Fib returns 1 Fib(3)
Fib(5) Fib returns 2 Fib(4)
Main Algorithm answer lt- Fib(5)
45
Tracing with Multiple Recursive Calls
Fib(4) Fib returns 1 2
Fib(5) Fib returns 2 Fib(4)
Main Algorithm answer lt- Fib(5)
46
Tracing with Multiple Recursive Calls
Fib(5) Fib returns 2 3
Main Algorithm answer lt- Fib(5)
47
Tracing with Multiple Recursive Calls
Main Algorithm answer lt- 5
48
Mutual Recursion
  • Recursion doesnt always occur because a routine
    calls itself...
  • Mutual Recursion occurs when two routines call
    each other.

A
B
A
B
49
Mutual Recursion Example
  • Problem Determine whether a number, N, is odd or
    even.
  • If N is equal to 0, then n is even
  • N is odd if N-1 is even

50
Example Implementation
  • function Odd returnsa Boolean (n iot in Num)
  • if (n 0) then
  • Odd returns FALSE
  • else
  • Odd returns Even (n - 1)
  • endif
  • endfunction //Odd
  • function Even returnsa Boolean (n iot in Num)
  • if (n 0) then
  • Even returns TRUE
  • else
  • Even returns Odd (n - 1)
  • endif
  • endfunction //Even

51
Building Recursive Modules
  • Decide on the terminating condition
  • Decide the final actions when you terminate
  • There may be none
  • If you are computing something, this usually
    starts a ripple of returned data
  • Decide how to take a step closer to terminating
  • think about how to make your original, complex
    problem simpler
  • Decide how to call a clone of this module
  • Decide what work to do at this step in recursion

52
Questions?
53
Design by Contract
54
An Example Module
  • function Fibonacci returnsa Num(n isoftype in
    num)
  • // Returns Nth fibonacci number
  • if ((n0) OR (n1)) then
  • Fibonacci returns 1
  • else
  • Fibonacci returns Fibonacci(n-1)
    Fibonacci(n-2)
  • endif
  • endfunction // Fibonacci

55
Correctness
What if we call it via some_var lt-
Fibonacci(-1) or
some_var lt- Fibonacci(4.3) The module will never
reach its terminating condition and willnever
end!
56
A First Try at a Correction
  • function Fibonacci returnsa num (n iot in num)
  • // Returns Nth fibonacci number
  • // Ensure n is a non-negative integer
  • if ((n lt 0) or ((n mod 1) lt gt 0)) then
  • print( "Illegal n in function!" )
  • else
  • // Old module body follows...
  • if((n 0) OR (n 1)) then
  • Fibonacci returns 1
  • else
  • New_Fibonacci returns Fibonacci(n-1)
  • Fibonacci(n-2)
  • endif
  • endif
  • endfunction // Fibonacci

57
But That Solution Had Problems!
  • Inefficient because were doing the test
    unnecessarily at each iteration
  • Functions must always return a value
  • Mixes correctness part with carrying out
    algorithm part
  • Doing more than one thing
  • Functions cannot print!

58
Design by Contract
  • Like a business contract (house-building)
  • The modules client is the caller of the module.
  • The supplier is the called module
  • The pre-condition states the responsibilities of
    the client
  • The post-condition states the guarantees made by
    the supplier

59
Module Documentation as a Contract
  • Make both client and supplier responsibilities
    explicit as part of documentation.
  • Both client and supplier know what is expected of
    them and what to expect of the other.
  • function Fibonacci returnsa num(n isoftype in
    num)
  • // Purpose Returns nth fibonacci number
  • // Pre-condition n is a non-negative integer
  • // Post-condition The returned number is the
    nth// number in the fibonacci
  • // sequence

60
Questions?
61
Introduction to Data Abstraction Records
62
Where ya been?Krogers.Whats in the bag?
LB
  • Answer 1
  • beans
  • canned peaches
  • bread
  • chips
  • coke
  • dental floss
  • ice cream
  • shoe polish
  • John Tesh CD
  • carrots
  • Answer 2
  • groceries

63
Data Abstraction
  • Separating the essence from the particular
    instance or implementation.
  • The most fundamental technique
  • Descriptive identifiers that are brief and
    informative (not cryptic or cute)
  • Example
  • For the purpose of representing an employees
    ID number, which one features the highest data
    abstraction?
  • this_num isofype Num
  • someone_num isoftype Num
  • employee_ID_num isoftype Num

64
Data Abstraction
  • Data Abstraction allows us to
  • Combine data that belongs together
  • Consider the logical grouping of data
  • Apart from the specific implementation
  • Records are the mechanism for data grouping.
  • Defined in the algorithm
  • A heterogeneous collection of data(we can mix
    different types of data in a single structure)

65
Representing Related Data
  • Information concerning a student
  • name isoftype String
  • age isoftype Num
  • is_male isoftype Boolean
  • letter_grade isoftype Char
  • This should be abstractly grouped together!

66
Grouping Related Data Together
name (String)
age (Num)
is_male (Boolean)
Letter_grade (Char)
67
Record Definition Example
  • Student_Type definesa record
  • name isoftype String
  • age isoftype Num
  • is_male isoftype Boolean
  • letter_grade isoftype Char
  • endrecord // Student_Type
  • Instead of a collection of 4 variables, we have
    defined a new data type and now have the ability
    to create variables of Student_Type, each with
    the appropriate information.


68
Record Templates
LB
  • Definition
  • ltType Namegt definesa record
  • ltfield definitionsgt
  • endrecord
  • Declaration
  • ltIdentifiergt isoftype ltType Namegt


69
Record Example
  • Student_Type definesa record
  • name isoftype String
  • age isoftype Num
  • is_male isoftype Boolean
  • letter_grade isoftype Char
  • endrecord // Student_Type
  • Stu1, Stu2, Stu3 isoftype Student_Type
  • This creates three variables of type
    Student_Type. Each of these variables contains
    information about name, age, is_male, and
    letter_grade.


70
Creating New Data Types
  • We use records to construct new user-defined
    data types
  • The newly created data type is treated like any
    of the built-in types
  • Cannot read or print user defined data types
    directly. Since the new type is new to the
    language, read and print dont know how to
    process the request.
  • Creating variables of a new data type is a
    two-step process define then declare
  • Creating the new data type does not provide any
    variables, only the template by which variables
    may then be declared.

71
Creating New Data Types Example
  • Task
  • Create a database to keep track of the kids in an
    elementary school
  • To make the example simple, we will only store
  • Student number
  • Age
  • Grade in math this year


72
Creating New Data Types Example
  • Step 1 Define the new type
  • Kid_Record definesa Record
  • student_num isoftype Num
  • age isoftype Num
  • grade isoftype Char
  • endrecord
  • Step 2 Declare Record variables of this new
    type
  • mary, zach, herbert isoftype Kid_Record
  • best_grade isoftype Char

73
Accessing Fields of Records
  • We can access the individual fields of a record
    using the dot (.) operator
  • ltvar_namegt.ltfield_namegt
  • Examples
  • mary.student_num lt- 45137
  • mary.age lt- 13
  • mary.grade lt- A
  • best_grade lt- mary.grade
  • zach.grade lt- best_grade
  • zach.age lt- 12


74
Operators and Records
  • Assignment works just as before with built-in
    types (both sides must be of the same type)
  • // assigns ALL fields in single op
  • zach lt- mary
  • Printing and reading can only take built-in types
    as parameters, so we print and read fields, not
    records.
  • read(zach.student_num, zach.age, zach.grade)
  • print(zach.student_num, zach.age, zach.grade)

75
Using New Data Types
  • Note Items of the form
  • some_record_var.some_field
  • are L-values - they may appear on the left of an
    assignment may be passed as in, in/out, or out
    parameters.

76
Combining Abstractions
  • Often, data abstractions (for example, records)
    need corresponding procedural abstractions
    (modules) as helpers.
  • Common examples include
  • Modifier modules procedures usedto read in or
    update data values
  • Accessor modules procedures used to print out
    information in a record, or functions which
    return data values to other modules
  • We will revisit this idea when we talk about
    behavioral abstractions later in the course

77
Combining Abstractions
  • For example
  • Student_Rec definesa Record
  • name isoftype String
  • ssn isoftype Num
  • num_hours isoftype Num
  • endrecord
  • procedure Print_Student(somebody isoftype
    in Student_Rec)
  • // An accessor module which prints out all //
    data values stored in a Student_Rec
    print(Name , somebody.name)
  • print( SSN , somebody.ssn )
  • print( Hours, somebody.num_hours )
  • endprocedure

78
Combining Abstractions
  • procedure Read_Student (somebody isoftype out
    Student_Rec)
  • // A modifer module which obtains data// values
    and stores them in a Student_Rec
  • print(Enter the students name )
  • read( somebody.name )
  • print(Enter the students ssn )
  • read( somebody.ssn )
  • print( Enter the students hours taken )
  • read( somebody.num_hours )
  • endprocedure // Read_Student

79
Combining Abstractions
  • ...
  • Student_1 isoftype Student_Rec
  • // call to modifier
  • Read_Student(Student_1)
  • // call to accessor
  • Print_Student(Student_1)
  • ...
  • Student_2 isoftype Student_Rec
  • // call to modifier
  • Read_Student(Student_2)
  • // call to accessor
  • Print_Student(Student_2)

80
Records Within Records
  • There is nothing to prevent us from placing
    records inside of records (a field within a
    record)
  • Date_Type definesa record
  • day, month, year isoftype num
  • Endrecord
  • Student_Type definesa record
  • name isoftype string
  • gpa isoftype num
  • birth_day isoftype Date_Type
  • graduation_day isoftype Date_Type
  • endrecord

81
Record Within Records
  • Date_Type
  • Student_Type
  • bob isoftype Student_Type
  • bob.birth_day.month lt- 6

birth_day
graduation_day
82
Types vs. Variables
  • TYPE Definitions
  • Create templates for new kinds of variables
  • Do not create a variable no storage space is
    allocated
  • Have unlimited scope
  • VARIABLE Declarations
  • Actually create storage space
  • Have limited scope - only module containing the
    variable can see it
  • Must be based on an existing data type

83
Anonymous Data Types
  • This_Record isoftype record
  • silly isoftype Num
  • stupid isoftype Char
  • endrecord // This_Record
  • Anonymous data types combine the declaration of a
    complex variable with a data type definition.
  • Thus, the data type itself has no name.
  • Some languages allow this
  • Removes benefits of data typing
  • Is in general bad do not do this even if a
    language allows it

84
Anonymous Data Types
  • If two different variables are anonymous data
    types with identical structure, then they can
    hold the same data, but
  • They are not of the same type they are of no
    type
  • Cannot assign one to another
  • Cannot pass grouped data between them via
    parameter
  • Must assign field-by-field
  • Must make changes in multiple places
  • Dont do it!!
  • In our pseudo-code, cannot do it

85
Questions?
86
(No Transcript)
Write a Comment
User Comments (0)
About PowerShow.com