Introduction

Procedure & Function

  • Subprograms are collections of statements that define parameterized computations
  • There are two kinds of subprograms:
    1. Functions return values
    2. Procedure do not
  • In most of the languages do not include procedures as a separate form of subprogram (functions that can be defined not to return values can be used as procedures)

Execution

  • Each subprogram has a single entry point
  • The calling subprogram is suspended during execution of the called subprogram (i.e., there is only one subprogram in execution in the given time)
  • Except the program is terminated, control always return to the caller at the subprogram called statement when the called subprogram’s execution terminate

Definition

  • Subprogram Definition

    • describes the interface to and the actions of the subprogram abstraction

      1
      2
      3
      4
      void f(){
      cout << "haha" << endl;
      return;
      }
      • f is the definition of this subprogram
    • In Python, function definitions are executable

    • In all other languages, they are non-executable
    • Executable function definition:
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      is_advanced_operator_allowed = True

      if is_advanced_operator_allowed:
      def is_even(n):
      print("thinking...")
      return n % 2 == 0
      else:
      def is_even(n):
      print("thinking...")
      if n == 1:
      return False
      elif n == 2:
      return True
      else:
      return is_even(n-2)

      print(is_even(10))
  • Subprogram Call
    • an explicit request that the subprogram be executed (fun())
  • Subprogram Header
    • the first part of the definition, including the name, the kind of subprogram, and the parameters
  • Parameter Profile
    • the number, order, and types of its parameters
  • Protocol
    • the parameter profile and the return type
  • Subprogram Declaration
    • the protocol of the subprogram (prototype in C/C++)
      1
      int sum(int, int);
  • Parameter (formal parameter)
    • a variable listed in the subprogram header and used in the subprogram
      1
      int sum(int a, int b) { }  // a and b are the parameters
  • Argument (actual parameter)
    • the actual input supplied in the subprogram call statement to the subprogram
      1
      sum(14, 23) // arguments

Correspondence

  1. Positional

    • the binding of arguments to parameters is by position
    • Advantage: Simple and effective
  2. Keyword (in Python, JavaScript, C#)

    • the name of the parameter is in form of a keyword, to which an argument is to be bound is specified with the argument
      1
      2
      3
      4
      5
      6
      7
      def f(a, b, c):
      print("a is", a)
      print("b is", b)
      print("c is", c)

      f(b=1, a=2, c=3)
      f(3, c=9, b=1)
    • Advantage: arguments can appear in different order
    • Disadvantage: users are able to know the parameter’s names

Parameter Default Values

  • parameters can have default values if no argument is passed
  • Note: the default parameters must appear last(because parameters are positionally associated)
  • Remind: the default parameters should be assign in subprogram declaration (if have)

    • default parameter in C++

      1
      2
      3
      4
      5
      6
      7
      8
      9
      int sum(int, int = 3);

      int main() {
      cout << sum(1) << endl; // 4
      }

      int sum(int a, int b){
      return a + b;
      }
    • list of variable number of parameters in Python (*)

      1
      2
      3
      4
      5
      def fun(x, *args):
      print(type(args)) # tuple
      print(x, args) # 1, (2, 3, "dq")

      fun(1, 2, 3, "dq")
    • named keyword argument in Python (**)

      1
      2
      3
      4
      5
      6
      7
      def fun(**args):
      print(type(args)) # dict
      for key, value in args.items():
      print(key, "->", value) # name -> doge
      # age -> 17

      fun(name = "doge", age = 17)

Parameter Passing Methods

Passing Value

  1. Pass-by-Value

    • the value of the argument is used to initialize the corresponding parameter
    • normally implemented by simply copying
      1
      2
      3
      4
      5
      6
      7
      8
      int sum(int a, int b){
      return a + b;
      }
      int main() {
      int a = 3;
      int b = 5;
      cout << sum(a, b) << endl;
      }
    • Advantage: no side-effect
    • Disadvantage: require additional storage
  2. Pass-by-Result

    • no value is transmitted to the subprogram, the parameter simply acts as a local variable
    • i.e., the value is transmitted to the caller’s argument when control return to the caller by coping
      1
      2
      3
      4
      5
      6
      7
      8
      9
      subroutine foo(result x)
      x = x * 2
      end subroutine

      main
      variable a = 3
      call foo(a)
      print a // prints 6
      end main
    • Potential problem:
      call foo(a, a): in this case, what should a be?
  3. Pass-by-Value-Result

    • combination of pass-by-value and pass-by-result
    • i.e., copying the value of argument to the parameter, then do some change on the parameter in the subprogram, then copying the value of parameter to the argument when return
      • Disadvantage: combination of pass-by-value and pass-by-result

Passing Object

  1. Pass-by-Reference

    • pass the reference to the argument variable (can be simulated in pass-by-value of pointers for languages that not support reference)
      • copying the address of arguments instead of the whole data structure
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        void f(int& a){
        a = 99;
        return;
        }

        int main(){
        int b = 0;
        f(b);
        cout << b << endl;
        }
    • Advantage: passing is efficient because there is no copying and duplicate storage
    • Disadvantage:
      • slower access (indirect access)
      • potential for the side effect
  2. Pass-by-Sharing

    • copy the reference argument (point to an object) and pass to the parameter
    • Note: it is for object only (so need to wrapper the primitive data values in we want to use Pass-by-Sharing in those values)
    • Python / Ruby use Pass-by-Sharing
      Everything is concidered as an object (all variables are considered as references to some objects)
    • Java also use pass-by-sharing for object arguments
      Consider Pass-by-Sharing is just similar to Pass-by-value (copying), so simply use Pass-by-Value (where the value is a reference)
  • Pass-by-Renerence vs Pass-by-Sharing

    • Implementation of Pass-by-Renerence (similated using pointer) in C++

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      class Dog{
      public:
      string name;
      Dog(string name): name(name) {};
      };

      void fun(Dog*& d){ // & - reference Dog* a pointer to Dog type
      d->name = "corgi";
      d = new Dog("shiba");
      }

      int main(){
      Dog* d = new Dog("husky");
      fun(d); // passing-by-reference
      cout << d->name << endl; // outputs: shiba
      return 0;
      }
    • Implementation of Pass-by-Sharing in Java

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      class Dog{
      public String name;
      Dog(String name){
      this.name = name;
      }
      }

      class Hello {
      public static void fun(Dog d){
      d.name = "corgi";
      d = new Dog("shiba");
      }

      public static void main(String[] args){
      Dog d = new Dog("husky");
      fun(d); // passing-by-sharing
      System.out.println(d.name); // outputs: corgi
      }
      }
    • The main different is the new assignment for the parameter in the subprogram:
      • Pass-by-Reference is passing a reference to the argument
      • Pass-by-Sharing is passing a copied reference from the argument
        Therefore, when there is a new assignment to the parameter, the argument is also changed in Pass-by-Reference but not Pass-by-Sharing

Parameters

Multidimensional Arrays

  • access an element in a multi-dimensional array, a storage mapping function (address calculation) has to be built

    • int a[4][2] = {{11,12}, {21,22}, {31,32}, {41,42}};

      Memory Address (One-dimensional)
      11 12 21 22 31 32 41 42 ...
      • address of a[3][1] = (address of a[0][0]) + (3 2 + 1) (sizeof int)
  • C/C++ Implementation

    • Porblems:

      1. C/C++ requires programmer to include the declared size of all (but not the first dimension) in the array parameter

        • It is necessary for the programmer to declare the parameter like
          void f(int a[2][3][8]) or void f(int a[][3][8])(but not the first dimension)
      2. sizeof array in a function

        1
        2
        3
        4
        5
        6
        7
        8
        9
        void f(int a[10]){
        cout << sizeof(a) << endl; // 8
        }

        int main(){
        int a[10] = {1,2,3,4,5,6,7,8,9,0};
        cout << sizeof(a) << endl; // 40: 4 * 10
        f(a); // 8: sizeof the pointer instead of the array
        }
    • Solution:
      • We can use a flexible workaround
        • pass a pointer to the array and the sizes of the dimensions as other parameters
          void f(int* a, int firstDSize, int secondDSize, int thirdDSize)
  • Java/C#/Python Implementation
    • Arrays are objects in those languages, so the multi-dimensional array is single-dimensioned
      • int a[][] = {{11}, {21,22,23}, {31,32}};
        Memory Address (One-dimensional)
        Array Object Array Object Array Object ...
        11 21 22 23 31 32 ...
      • Access the size of array:
        • l.length in Java
        • len(l) in Python

Subprograms

  • There are situations in which a subprogram is a parameter of another subprogram

  • C/C++ Implementation

    • functions can be passed as function pointers (*p)(...)
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      void f(int x){
      int a, b, c;
      cout << "f() is called, " << x << endl;
      }
      void g(void (*p)(int), int x){
      p(x);
      }
      int main(){
      g(f, 3); // f() is called, 3
      return 0;
      }
  • Python Implementation

    • functions in Python are first-class citizens and simply objects
      so it can be simply passed as parameter like any other Objects
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      def f(x):
      print("f() is called,", x)
      def p(x):
      print("p() is called,", x + 1)

      def g(fun, x):
      fun(x)

      g(f, 2) # f() is called, 2
      g(p, 2) # p() is called, 3

Closures

  • it is a subprogram and the referencing environment where it was defined
  • the referencing environment is needed if the subprogram can be called from any arbitrary place in the program
  1. A static-scoped language that does not permit nested subprograms doesn’t need closures

    • Implementation in C++:
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      int global_var = 4;
      void f(){
      int a = 1, b = 2, c = 3;
      cout << "f() is called, local = " << a << ", global = " << global_var << endl;
      }
      void g(void (*p)()){
      p();
      }
      int main(){
      f(); // f() is called, local = 1, global = 4
      g(f); // f() is called, local = 1, global = 4
      return 0;
      }
      • the referencing environment in f (called from any arbitrary place in the program) is the local variables (a, b, c) and the global variables which is same as directly calling, so the static-scoped language that does not support nested programming doesn’t need closures
  2. Closures are necessary for a subprogram that can access variables in the nesting scopes and it can called from abywhere

    • Implementation in Python:
      1
      2
      3
      4
      5
      6
      7
      8
      def adder(x):
      def template_adder(y): # nested subprogram
      return x+y
      return template_adder
      # actually returning a closure that has the referencing environment as adder

      add_five = adder(5) # the closures (<function adder.<locals>.template_adder at 0x55dec94ab020>)
      print(add_five(2)) # 7
      • the referencing environment of template_adder has x which is outside the definition of template_adder, but because Python supports closures, so x is also passed through to the template_adder
      • the clousre returned from adder is both the function and the referencing environment
  • closures actually extended lifetime to some variables, in case, x is extended as the function adder has already ended

Lambdas

  • anonymous functions (which syntax is much more simplier and readable than defining a function) using the keyword lambda
    • Implementation in Python:
      1
      2
      3
      4
      5
      def adder(x):
      return lambda y: x + y

      add_five = adder(5)
      print(add_five(2))
      • In case, the function named template_adder is not important as it would be “rename” later
        (add_five = adder(5): the function template_adder is actually renamed to add_five)

Polymorphic Subprograms

  • Polymorphic subprograms are subprograms that can operate on different types of data
  1. Adhoc Polymorphism

    • Overloaded subprograms provide a particular kind of polymorphism called adhoc polymorphism
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      void printType(int x){
      cout << "int is the best!" << endl;
      }

      void printType(float x){
      cout << "float is the best!" << endl;
      }

      int main(){
      printType(1); // int is the best!
      printType(1.0f); // float is the best!
      printType(true); // int is the best!
      printType(1.0); // ERROR
      }
  2. Subtype Polymorphism

  • A parameter of type X can take any object of type X or any type derived from X
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    class Food {
    public:
    virtual void eat() {
    cout << "Eating food." << endl;
    }
    };

    class Apple : public Food {
    public:
    void eat() {
    cout << "Eating apple." << endl;
    }
    };

    class Water : public Food {
    public:
    void drink() {
    cout << "Drinking water." << endl;
    }
    };

    int main() {
    Food* food = new Food();
    Food* apple = new Apple();
    Food* water = new Water();

    food->eat(); // Eating food.
    apple->eat(); // Eating apple.
    water->eat(); // Eating food. (since the Water class doesn't override the eat() method)

    return 0;
    }