ch9-Short (1)
ch9-Short (1)
Subprograms
Chapter 9 Topics
• Introduction
• Fundamentals of Subprograms
• Design Issues for Subprograms
• Local Referencing Environments
• Parameter-Passing Methods
• Parameters That Are Subprograms
• Calling Subprograms Indirectly
• Overloaded Subprograms
• Generic Subprograms
• Design Issues for Functions
• User-Defined Overloaded Operators
• Closures
• Coroutines
Copyright © 2012 Addison-Wesley. All rights reserved. 1-2
Introduction
• In mode
• Out mode
• Inout mode
• By textual substitution
• Formals are bound to an access method at
the time of the call, but actual binding to
a value or address takes place at the time
of a reference or assignment
• Allows flexibility in late binding
• Implementation requires that the
referencing environment of the caller is
passed with the parameter, so the actual
parameter address can be calculated
Copyright © 2012 Addison-Wesley. All rights reserved. 1-19
Implementing Parameter-Passing Methods
• Similar to Ada
• Arrays are objects; they are all single-
dimensioned, but the elements can be
arrays
• Each array inherits a named constant
(length in Java, Length in C#) that is set to
the length of the array when the array
object is created
• A JavaScript closure:
function makeAdder(x) {
return function(y) {return x + y;}
}
...
var add10 = makeAdder(10);
var add5 = makeAdder(5);
document.write(″add 10 to 20: ″ + add10(20) +
″<br />″);
document.write(″add 5 to 20: ″ + add5(20) +
″<br />″);
- The closure is the anonymous function returned
by makeAdder
Copyright © 2012 Addison-Wesley. All rights reserved. 1-37
Closures (continued)
• C#
- We can write the same closure in C# using a nested
anonymous delegate
- Func<int, int> (the return type) specifies a delegate
that takes an int as a parameter and returns and int
static Func<int, int> makeAdder(int x) {
return delegate(int y) {return x + y;};
}
...
Func<int, int> Add10 = makeAdder(10);
Func<int, int> Add5 = makeAdder(5);
Console.WriteLine(″Add 10 to 20: {0}″, Add10(20));
Console.WriteLine(″Add 5 to 20: {0}″, Add5(20));