0% found this document useful (0 votes)
10 views54 pages

PL08 Subprograms

Uploaded by

maytryark
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views54 pages

PL08 Subprograms

Uploaded by

maytryark
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

Programming  

Languages  –
Subprograms
Jongwoo  Lim
Chapter  Topics
• Introduc1on  
• Fundamentals  of  Subprograms  
• Design  Issues  for  Subprograms  
• Local  Referencing  Environments  
• Parameter-­‐passing  Methods  
• Parameters  That  Are  Subprograms  
• Overloaded  Subprograms,  Generic  Subprograms  
• Design  Issues  for  Func1ons  
• User-­‐Defined  Overloaded  Operators  
• Corou1nes © 2009 Addison-Wesley.
Introduc9on
• Two  fundamental  abstrac1on  facili1es  
-­‐ Process  abstrac1on    
• Emphasized  from  early  days  
-­‐ Data  abstrac1on  
• Emphasized  in  the  1980s

© 2009 Addison-Wesley.
Fundamentals  of  Subprograms
• Each  subprogram  has  a  single  entry  point  
• The  calling  program  is  suspended  during  execu1on  of  the  called  
subprogram  
• Control  always  returns  to  the  caller  when  the  called  
subprogram’s  execu1on  terminates

© 2009 Addison-Wesley.
Basic  Defini9ons
• A  subprogram  defini9on  describes  the  interface  to  and  the  
ac1ons  of  the  subprogram  abstrac1on  
-­‐ In  Python,  func1on  defini1ons  are  executable;  in  all  other  languages,  
they  are  non-­‐executable  
• A  subprogram  call  is  an  explicit  request  that  the  subprogram  be  
executed

© 2009 Addison-Wesley.
Basic  Defini9ons
• A  subprogram  header  is  the  first  part  of  the  defini1on,  including  
the  name,  the  kind  of  subprogram,  and  the  formal  parameters  
• The  parameter  profile  (aka  signature)  of  a  subprogram  is  the  
number,  order,  and  types  of  its  parameters  
• The  protocol  is  a  subprogram’s  parameter  profile  and,  if  it  is  a  
func1on,  its  return  type

© 2009 Addison-Wesley.
Basic  Defini9ons
• Func1on  declara1ons  in  C  and  C++  are  oYen  called  prototypes  
• A  subprogram  declara9on  provides  the  protocol,  but  not  the  
body,  of  the  subprogram  
• A  formal  parameter  is  a  dummy  variable  listed  in  the  subprogram  
header  and  used  in  the  subprogram  
• An  actual  parameter  represents  a  value  or  address  used  in  the  
subprogram  call  statement  

int Func(int i, int j);


int Func(int a, int b) { return a + b; }
int main() {
int sum = 0;
for (int i = 0; i < 10; ++i) sum = Func(sum, i);
...
© 2009 Addison-Wesley.
Actual/Formal  Parameter  Correspondence
• Posi1onal  
-­‐ The  binding  of  actual  parameters  to  formal  parameters  is  by  posi1on:  
the  first  actual  parameter  is  bound  to  the  first  formal  and  so  forth  
-­‐ Safe  and  effec1ve  

• Keyword  
-­‐ The  name  of  the  formal  parameter  to  which  an  actual  parameter  is  
to  be  bound  is  specified  with  the  actual  parameter  
-­‐ Advantage:  Parameters  can  appear  in  any  order,  thereby  avoiding  
parameter  correspondence  errors  
-­‐ Disadvantage:  User  must  know  the  formal  parameter’s  names  

sum(length = my_length, list = my_array, sum = my_sum)


sum(my_length, sum = my_sum, list = my_array)
© 2009 Addison-Wesley.
Formal  Parameter  Default  Values
• In  certain  languages  (e.g.,  C++,  Python,  Ruby,  Ada,  PHP),  formal  
parameters  can  have  default  values  (if  no  actual  parameter  is  
passed)  
-­‐ In  C++,  default  parameters  must  appear  last  because  parameters  are  
posi1onally  associated  

def compute_pay(income, exemptions = 1, tax_rate)


...
pay = compute_pay(20000.0, tax_rate = 0.15)

float compute_pay(float income, float tax_rate,


int exemption = 1)
...
pay = compute_pay(20000.0, 0.15)

© 2009 Addison-Wesley.
Variable  Numbers  of  Parameters
• Variable  numbers  of  parameters  
-­‐ C#  methods  can  accept  a  variable  number  of  parameters  as  long  as  
they  are  of  the  same  type  –  the  corresponding  formal  parameter  is  
an  array  preceded  by  params  
-­‐ In  Ruby,  the  actual  parameters  are  sent  as  elements  of  a  hash  literal  
and  the  corresponding  formal  parameter  is  preceded  by  an  asterisk.    
-­‐ In  Python,  the  actual  is  a  list  of  values  and  the  corresponding  formal  
parameter  is  a  name  with  an  asterisk  
-­‐ In  Lua,  a  variable  number  of  parameters  is  represented  as  a  formal  
parameter  with  three  periods;  they  are  accessed  with  a  for  
statement  or  with  a  mul1ple  assignment  from  the  three  periods

© 2009 Addison-Wesley.
Ruby  Blocks
-­‐ Ruby  includes  a  number  of  iterator  func1ons,  which  are  oYen  used  
to  process  the  elements  of  arrays  
-­‐ Iterators  are  implemented  with  blocks,  which  can  also  be  defined  by  
applica1ons  
-­‐ Blocks  are  acached  methods  calls;  they  can  have  parameters  (in  
ver1cal  bars);  they  are  executed  when  the  method  executes  a  yield  
statement  

© 2009 Addison-Wesley.
Ruby  Blocks
-­‐ Ruby  includes  a  number  of  iterator  func1ons.  
-­‐ Iterators  are  implemented  with  blocks  
-­‐ Blocks  are  acached  methods  calls  

def fibonacci(last)
first, second = 1, 1
while first <= last
yield first
first, second = second, first + second
end
end

puts "Fibonacci numbers less than 100 are:"


fibonacci(100) {|num| print num, " "}
puts

Fibonacci numbers less than 100 are:


1 1 2 3 5 8 13 21 34 55 89

© 2009 Addison-Wesley.
Procedures  and  Func9ons  
• There  are  two  categories  of  subprograms  
-­‐ Procedures  are  collec1on  of  statements  that  define  parameterized  
computa1ons  
-­‐ Func9ons  structurally  resemble  procedures  but  are  seman1cally  
modeled  on  mathema1cal  func1ons  
• They  are  expected  to  produce  no  side  effects  
• In  prac1ce,  program  func1ons  have  side  effects

© 2009 Addison-Wesley.
Design  Issues  for  Subprograms
• Are  local  variables  sta1c  or  dynamic?    
• Can  subprogram  defini1ons  appear  in  other  subprogram  
defini1ons?    
• What  parameter  passing  methods  are  provided?  
• Are  parameter  types  checked?  
• If  subprograms  can  be  passed  as  parameters  and  subprograms  
can  be  nested,  what  is  the  referencing  environment  of  a  passed  
subprogram?  
• Can  subprograms  be  overloaded?  
• Can  subprogram  be  generic?
© 2009 Addison-Wesley.
Local  Referencing  Environments
• Local  variables  can  be  stack-­‐dynamic    
-­‐ Advantages  
• Support  for  recursion  
• Storage  for  locals  is  shared  among  some  subprograms  
-­‐ Disadvantages  
• Alloca1on/de-­‐alloca1on,  ini1aliza1on  1me  
• Indirect  addressing  
• Subprograms  cannot  be  history  sensi1ve  

• Local  variables  can  be  sta1c  


-­‐ Advantages  and  disadvantages  are  the  opposite  of  those  for  stack-­‐
dynamic  local  variables

© 2009 Addison-Wesley.
Seman9c  Models  of  Parameter  Passing
-­‐ In  mode  
-­‐ Out  mode  
-­‐ Inout  mode

© 2009 Addison-Wesley.
Conceptual  Models  of  Transfer
• Physically  move  a  path  :  copy  the  object  
• Move  an  access  path  :  provide  an  alias  to  the  object

© 2009 Addison-Wesley.
Pass-­‐by-­‐value  (In  Mode)
• The  value  of  the  actual  parameter  is  used  to  ini1alize  the  
corresponding  formal  parameter  
-­‐ Normally  implemented  by  copying  
-­‐ Can  be  implemented  by  transmiing  an  access  path  but  not  
recommended  (enforcing  write  protec1on  is  not  easy)  
-­‐ Disadvantages  (if  by  physical  move):
addi1onal  storage  is  required  (stored  twice)  and
the  actual  move  can  be  costly  (for  large  parameters)  
-­‐ Disadvantages  (if  by  access  path  method):
must  write-­‐protect  in  the  called  subprogram  and
accesses  cost  more  (indirect  addressing)

© 2009 Addison-Wesley.
Pass-­‐by-­‐result  (Out  Mode)
• When  a  parameter  is  passed  by  result  
-­‐ No  value  is  transmiced  to  the  subprogram  
-­‐ The  corresponding  formal  parameter  acts  as  a  local  variable  
-­‐ Its  value  is  transmiced  to  caller’s  actual  parameter  when  control  is  
returned  to  the  caller,  by  physical  move  
• Require  extra  storage  loca1on  and  copy  opera1on  

void Fixer(out int x, out int y) { x = 17; y = 35; }


...
f.Fixer(out a, out a);

void DoIt(out int x, out int index) { x = 17; index = 42; }


...
sub = 21;
f.DoIt(list[sub], sub);

© 2009 Addison-Wesley.
Pass-­‐by-­‐value-­‐result  (Inout  Mode)
• A  combina1on  of  pass-­‐by-­‐value  and  pass-­‐by-­‐result  
-­‐ Some1mes  called  pass-­‐by-­‐copy  
• Formal  parameters  have  local  storage  
• Disadvantages:  
-­‐ Those  of  pass-­‐by-­‐result  
-­‐ Those  of  pass-­‐by-­‐value  

© 2009 Addison-Wesley.
Pass-­‐by-­‐reference  (Inout  Mode)
• Pass  an  access  path  
-­‐ Also  called  pass-­‐by-­‐sharing  
-­‐ Advantage:  passing  process  is  efficient  (no  copying  and  no  duplicated  
storage)  
-­‐ Disadvantages  
• Slower  accesses  to  formal  parameters  (due  to  indirec1on,  
compared  to  pass-­‐by-­‐value)  
• Poten1als  for  unwanted  side  effects  (collisions)  
• Unwanted  aliases  (access  broadened)

© 2009 Addison-Wesley.
Pass-­‐by-­‐reference  (Inout  Mode)
• Pass  an  access  path  

void fun(int& first, int& second) ...

fun(total, total);
fun(list[i], list[j]); // if i == j, ...
fun1(list[i], list); // if list[j] is accessed and j==i

int* global;
void main() { ... sub(global); ... }
void sub(int* param) { ... }

© 2009 Addison-Wesley.
Pass-­‐by-­‐name  (Inout  Mode)
• By  textual  subs1tu1on  
-­‐ Formals  are  bound  to  an  access  method  at  the  1me  of  the  call,  but  
actual  binding  to  a  value  or  address  takes  place  at  the  1me  of  a  
reference  or  assignment  
-­‐ Allows  flexibility  in  late  binding  
-­‐ Used  for  macros  in  assembly  and  generic  parameters  of  the  generic  
subprograms  in  C++  and  Ada.  

template <typename T> inline


T max(const T& a, const T& b) { return a > b ? a : b; }

...
int i = 10, j = 20;
int m = max<int>(i, j);
...

© 2009 Addison-Wesley.
Implemen9ng  Parameter-­‐passing  Methods
• In  most  languages,  parameter  communica1on  takes  place  thru  
the  run-­‐1me  stack  
• Pass-­‐by-­‐reference  are  the  simplest  to  implement;  only  an  address  
is  placed  in  the  stack  
• A  subtle  but  fatal  error  can  occur  with  pass-­‐by-­‐reference  and  
pass-­‐by-­‐value-­‐result:  a  formal  parameter  corresponding  to  a  
constant  can  mistakenly  be  changed

© 2009 Addison-Wesley.
Implemen9ng  Parameter-­‐passing  Methods

void sub(int a, int b, int c, int d) { ... }


int main() { ... sub(w, x, y, z); ... }
   -­‐  pass  w  by  value,  x  by  result,  y  by  value-­‐result,  and  z  by  reference.
© 2009 Addison-Wesley.
Parameter  Passing  Methods  of
Major  Languages
• C  
-­‐ Pass-­‐by-­‐value  
-­‐ Pass-­‐by-­‐reference  is  achieved  by  using  pointers  as  parameters  

• C++  
-­‐ A  special  pointer  type  called  reference  type  for  pass-­‐by-­‐reference  
• Java  
-­‐ All  parameters  are  passed  are  passed  by  value  
-­‐ Object  parameters  are  passed  by  reference

© 2009 Addison-Wesley.
Parameter  Passing  Methods  of
Major  Languages
• Ada  
-­‐ Three  seman1cs  modes  of  parameter  transmission:  in,  out,  in  out;  in  
is  the  default  mode  
-­‐ Formal  parameters  declared  out  can  be  assigned  but  not  referenced;  
those  declared  in  can  be  referenced  but  not  assigned;  in  out  
parameters  can  be  referenced  and  assigned  
• C#
-­‐  Default  method:  pass-­‐by-­‐value  
-­‐ Pass-­‐by-­‐reference  is  specified  by  preceding  both  a  formal  parameter  
and  its  actual  parameter  with  ref  
• PHP:  very  similar  to  C#

© 2009 Addison-Wesley.
Parameter  Passing  Methods  of
Major  Languages
• Fortran  95
-­‐  Parameters  can  be  declared  to  be  in,  out,  or  inout  mode    
• Perl:  all  actual  parameters  are  implicitly  placed  in  a  predefined  
array  named  @_  
• Python  and  Ruby  use  pass-­‐by-­‐assignment  (all  data  values  are  
objects)

© 2009 Addison-Wesley.
Type  Checking  Parameters
• Considered  very  important  for  reliability  
• FORTRAN  77  and  original  C:  none  
• Pascal,  FORTRAN  90,  Java,  and  Ada:  it  is  always  required  
• ANSI  C  and  C++:  choice  is  made  by  the  user  
-­‐ Prototypes  
• Rela1vely  new  languages  Perl,  JavaScript,  and  PHP  do  not  require  
type  checking  
• In  Python  and  Ruby,  variables  do  not  have  types  (objects  do),  so  
parameter  type  checking  is  not  possible

© 2009 Addison-Wesley.
Mul9dimensional  Arrays  as  Parameters
• If  a  mul1dimensional  array  is  passed  to  a  subprogram  and  the  
subprogram  is  separately  compiled,  the  compiler  needs  to  know  
the  declared  size  of  that  array  to  build  the  storage  mapping  
func1on  
address(mat[i, j]) = address(mat[0, 0])
+ i * number_of_columns + j

number_of_columns

(i,j)

© 2009 Addison-Wesley.
Mul9dimensional  Arrays  as  Parameters:
C  and  C++
• Programmer  is  required  to  include  the  declared  sizes  of  all  but  
the  first  subscript  in  the  actual  parameter  
• Solu1on:  pass  a  pointer  to  the  array  and  the  sizes  of  the  
dimensions  as  other  parameters;  the  user  must  include  the  
storage  mapping  func1on  in  terms  of  the  size  parameters  

void fun(int matrix[][10]) { void fun(float* matrix,


... int num_rows,
} int num_cols) {
...
int main() { *(matrix + (row * num_cols)
int mat[5][10]; + col) = x;
... ...
fun(mat); }
...
}
© 2009 Addison-Wesley.
Mul9dimensional  Arrays  as  Parameters:  
Ada
• Ada  –  not  a  problem  
-­‐ Constrained  arrays:  size  is  part  of  the  array’s  type  
-­‐ Unconstrained  arrays:  declared  size  is  part  of  the  object  declara1on  

type Mat_Type is array(Integer range<>, Integer range<>)


of Float;
Mat_1 : Mat_Type(1..100, 1..20);

function Sum(Mat : in Mat_Type) return Float is


Total : Float := 0.0;
begin
for Row in Mat’range(1) loop
for Col in Mat’range(2) loop
Total := Total + Mat(Row, Col);
end loop;
end loop;
return Total;
end Sum;

© 2009 Addison-Wesley.
Mul9dimensional  Arrays  as  Parameters:  
Fortran
• Formal  parameter  that  are  arrays  have  a  declara1on  aYer  the  
header  
-­‐ For  single-­‐dimension  arrays,  the  subscript  is  irrelevant  
-­‐ For  mul1dimensional  arrays,  the  sizes  are  sent  as  parameters  and  
used  in  the  declara1on  of  the  formal  parameter,  so  those  variables  
are  used  in  the  storage  mapping  func1on

© 2009 Addison-Wesley.
Mul9dimensional  Arrays  as  Parameters:
 Java  and  C#
• 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  

float sum(float mat[][]) {


float total = 0.0f;
for (int row = 0; row < mat.length; ++row) {
for (int col = 0; col < mat[row].length; ++col) {
total += mat[row][col];
}
}
return total;
}

© 2009 Addison-Wesley.
Design  Considera9ons  for
Parameter  Passing
• Two  important  considera1ons  
-­‐ Efficiency  
-­‐ One-­‐way  or  two-­‐way  data  transfer  

• But  the  above  considera1ons  are  in  conflict  


-­‐ Good  programming  suggest  limited  access  to  variables,  which  means  
one-­‐way  whenever  possible  
-­‐ But  pass-­‐by-­‐reference  is  more  efficient  to  pass  structures  of  
significant  size

© 2009 Addison-Wesley.
Parameters  that  are  Subprogram  Names
• It  is  some1mes  convenient  to  pass  subprogram  names  as  
parameters  
• Issues:  
-­‐ Are  parameter  types  checked?  
-­‐ What  is  the  correct  referencing  environment  for  a  subprogram  that  
was  sent  as  a  parameter?

© 2009 Addison-Wesley.
Parameters  that  are  Subprogram  Names:  
Parameter  Type  Checking
• C  and  C++:  
-­‐ Func1ons  cannot  be  passed  as  parameters  
-­‐ Pointers  to  func1ons  can  be  passed  and  their  types  include  the  types  
of  the  parameters,  so  parameters  can  be  type  checked  
• FORTRAN  95  type  checks  
• Ada  does  not  allow  subprogram  parameters;  an  alterna1ve  is  
provided  via  Ada’s  generic  facility  
• Java  does  not  allow  method  names  to  be  passed  as  parameters

© 2009 Addison-Wesley.
Parameters  that  are  Subprogram  Names:  
Referencing  Environment
• Shallow  binding:  The  environment  of  the  call  statement  that  
enacts  the  passed  subprogram  
-­‐ Most  natural  for  dynamic-­‐scoped  languages  
• Deep  binding:  The  environment  of  the  defini1on  of  the  passed  
subprogram  
-­‐ Most  natural  for  sta1c-­‐scoped  languages  
• Ad  hoc  binding:  The  environment  of  the  call  statement  that  
passed  the  subprogram

© 2009 Addison-Wesley.
Parameters  that  are  Subprogram  Names:  
Referencing  Environment
function sub1() {
var x;
function sub() { alert(x); };
function sub2() {
var x;
x = 2;
sub3(sub);
};
function sub3(subx) {
var x;
x = 3;
subx();
};
x = 1;
sub2();
};

Shallow binding: x == 3
Deep binding: x == 1
Ad hoc binding: x == 2

© 2009 Addison-Wesley.
Overloaded  Subprograms
• An  overloaded  subprogram  is  one  that  has  the  same  name  as  
another  subprogram  in  the  same  referencing  environment  
-­‐ Every  version  of  an  overloaded  subprogram  has  a  unique  protocol  
-­‐ C++,  Java,  C#,  and  Ada  include  predefined  overloaded  subprograms    
-­‐ In  Ada,  the  return  type  of  an  overloaded  func1on  can  be  used  to  
disambiguate  calls  (thus  two  overloaded  func1ons  can  have  the  
same  parameters)  
-­‐ Ada,  Java,  C++,  and  C#  allow  users  to  write  mul1ple  versions  of  
subprograms  with  the  same  name  

void fun() { ... }


void fun(int a, int b) { ... }
void fun(float c = 0.0f) { ... } // Error!

© 2009 Addison-Wesley.
Generic  Subprograms
• A  generic  or  polymorphic  subprogram  takes  parameters  of  
different  types  on  different  ac1va1ons  
• Overloaded  subprograms  provide  ad  hoc  polymorphism  
• A  subprogram  that  takes  a  generic  parameter  used  in  a  type  
expression  which  describes  the  type  of  the  parameters  of  the  
subprogram  provides  parametric  polymorphism  
-­‐ A  cheap  compile-­‐1me  subs1tute  for  dynamic  binding

© 2009 Addison-Wesley.
Generic  Subprograms  -­‐  C++
-­‐ Versions  of  a  generic  subprogram  are  created  implicitly  when  the  
subprogram  is  named  in  a  call  or  when  its  address  is  taken  with  the  &  
operator  
-­‐ Generic  subprograms  are  preceded  by  a  template  clause  that  lists  
the  generic  variables,  which  can  be  type  names  or  class  names  

template <class Type>


Type max(Type first, Type second) {
return first > second ? first : second;
}

#define MAX(a, b) ((a) > (b) ? (a) : (b))


...

MAX(x++, y); // ((x++) > (y) ? (x++) : (y))


int a, b; max(a, b);
float c, d; max(c, d);
© 2009 Addison-Wesley.
Generic  Subprograms
• Java  5.0    (differences)  
-­‐ Generic  parameters  must  be  classes  (no  primi1ve  types)  
-­‐ Java  5.0  generic  methods  are  instan1ated  just  once  as  truly  generic  
methods  
-­‐ Restric1ons  can  be  specified  on  the  range  of  classes  that  can  be  
passed  to  the  generic  method  as  generic  parameters  
-­‐ Wildcard  types  of  generic  parameters    

public static <T> T doIt(T[] list) { ... }


public static <T extends Comparable> T doThat(T[] list) {
...
}

void printCollection(Collection<?> c) {
for (Object e: c) { System.out.println(e); }
}
© 2009 Addison-Wesley.
Generic  Subprograms
• C#  2005  
-­‐ Supports  generic  methods  that  are  similar  to  those  of  Java  5.0  
-­‐ One  difference:  actual  type  parameters  in  a  call  can  be  omiced  if  the  
compiler  can  infer  the  unspecified  type  

class MyClass {
public static T DoIt<T>(T param) {
...
}
}

int myInt = MyClass.DoIt(17); // DoIt<int>


string myStr = MyClass.DoIt(‘apples’); // DoIt<string>

© 2009 Addison-Wesley.
Generic  Subprograms
• Ada  
-­‐ Versions  of  a  generic  subprogram  are  created  by  the  compiler  when  
explicitly  instan1ated  by  a  declara1on  statement  
-­‐ Generic  subprograms  are  preceded  by  a  generic  clause  that  lists  the  
generic  variables,  which  can  be  types  or  other  subprograms  

generic
type Index_Type is (<>);
type Element_Type is private;
type Vector is array(Integer range <>) of Element_Type;
procedure Generic_Sort(List : in out Vector);
procedure Generic_Sort(List : in out Vector) is ...
end Generic_Sort;

procedure Integer_Sort is new Generic_Sort(


Index_Type => Integer, Element_Type => Integer,
Vector => Int_Array);
© 2009 Addison-Wesley.
Design  Issues  for  Func9ons
• Are  side  effects  allowed?  
-­‐ Parameters  should  always  be  in-­‐mode  to  reduce  side  effect  (like  Ada)  
• What  types  of  return  values  are  allowed?  
-­‐ Most  impera1ve  languages  restrict  the  return  types  
• C  allows  any  type  except  arrays  and  func1ons  
• C++  is  like  C  but  also  allows  user-­‐defined  types  
• Ada  subprograms  can  return  any  type  (but  Ada  subprograms  are  
not  types,  so  they  cannot  be  returned)  
• Java  and  C#  methods  can  return  any  type  (but  because  methods  
are  not  types,  they  cannot  be  returned)  
• Python  and  Ruby  treat  methods  as  first-­‐class  objects,  so  they  can  
be  returned,  as  well  as  any  other  class  
© 2009 Addison-Wesley.
User-­‐defined  Overloaded  Operators
• Operators  can  be  overloaded  in  Ada,  C++,  Python,  and  Ruby  
-­‐ An  Ada  example  

function "*" (A,B: in Vec_Type): return Integer is


Sum: Integer := 0;
begin
for Index in A'range loop
Sum := Sum + A(Index) * B(Index)
end loop
return sum;
end "*";
...
c : Integer;
c = a * b; -- a and b are of type Vec_Type

© 2009 Addison-Wesley.
Closures
• A  closure  is  a  subprogram  and  the  referencing  environment  
where  it  is  defined.  
-­‐ Closures  are  not  useful  if  a  sta1c-­‐scoped  language  does  not  allow  
nested  subprograms.  
-­‐ If  a  subprogram  can  be  called  anywhere  in  the  en1re  program,  the  
variables  defined  in  the  nes1ng  subprogram  may  need  life1mes  that  
are  of  the  en1re  program  :  unlimited  extent  

© 2009 Addison-Wesley.
Closures
• A  closure  is  a  subprogram  and  the  referencing  environment  
where  it  is  defined.  

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/>");

-> Add 10 to 20: 30


Add 5 to 20: 25

© 2009 Addison-Wesley.
Corou9nes
• A  corou9ne  is  a  subprogram  that  has  mul1ple  entries  and  
controls  them  itself  –  supported  directly  in  Lua  
-­‐ Also  called  symmetric  control:  caller  and  called  corou1nes  are  on  a  
more  equal  basis  
-­‐ A  corou1ne  call  is  named  a  resume  
-­‐ The  first  resume  of  a  corou1ne  is  to  its  beginning,  but  subsequent  
calls  enter  at  the  point  just  aYer  the  last  executed  statement  in  the  
corou1ne  
-­‐ Corou1nes  repeatedly  resume  each  other,  possibly  forever  
-­‐ Corou1nes  provide  quasi-­‐concurrent  execu1on  of  program  units  (the  
corou1nes);  their  execu1on  is  interleaved,  but  not  overlapped  
• e.g.  card  game  simula1on

© 2009 Addison-Wesley.
Corou9nes  Illustrated:  Possible  Execu9on  
Controls

© 2009 Addison-Wesley.
Corou9nes  Illustrated:  Possible  Execu9on  
Controls

© 2009 Addison-Wesley.
Corou9nes  Illustrated:  Possible  Execu9on  
Controls  with  Loops

© 2009 Addison-Wesley.
Summary
• A  subprogram  defini1on  describes  the  ac1ons  represented  by  the  
subprogram  
• Subprograms  can  be  either  func1ons  or  procedures  
• Local  variables  in  subprograms  can  be  stack-­‐dynamic  or  sta1c  
• Three  models  of  parameter  passing:  in  mode,  out  mode,  and  
inout  mode  
• Some  languages  allow  operator  overloading  
• Subprograms  can  be  generic  
• A  corou1ne  is  a  special  subprogram  with  mul1ple  entries

© 2009 Addison-Wesley.

You might also like