Wednesday, December 14, 2011

Functions

A function is a block of code within a program that does performs one task when called and then returns control back to the main program. This is a form of abstraction that allows for the construction of code that is easier to understand and debug. For example, let's say I want to write a program that simulates doing laundry. The steps for doing laundry are:
  1) sort whites and colors
  2) put a load in the washer
  3) add detergent
  4) start the machine
  5) move the load to the dryer
  6) start the dryer
  7) remove clothes and fold/hang up

I could write a program that does all of this in sequence, or I could write a function for each step.

Functions
General Structure


    function name (parameters)
        code
        return statement


Python


    def sort_clothes (color):
        """Sort clothes into a white pile and a color pile"""
     
        if (color == "white"):
            return "whites"

        else:
            return "colors"


C++


    string sort_clothes (string color)
    {
        if (color == "white")
            return "whites";

        else
            return "colors";
    }


Java


    String sortClothes (String color) {
        if (color == "white")
            return "whites";

        else
            return "colors";
    }

  • In Python you have to include the def keyword in order to specify that you are writing a function.
    • You must include parenthesis even if you don't have any parameters.
          def sort_clothes():
              # code
    •  You must include a colon after the parameter list.
    • The sentence enclosed in triple quotes is a docstring (documentation string). This is Python-specific and is used to comment functions.
      • docstrings are not required, but they must be the first line in a function if they are included.
      • when running a program in IDLE (the Python GUI) docstrings pop up as you type your function call.
    • Just like with variables, you don't have to declare types when writing a Python function.
  • In C++ a function header includes the functions return type, the function name, and a parameter list.
    • the function's code is enclosed within curly braces
    • The C++ compiler needs to know about all functions that are going to be used. For this reason, you should either:
      •  define them at the top before your main method
      • or declare them at the top and define them at the bottom. A function declaration is the function header followed by a semicolon:

        string sort_clothes (color);
  • In Java functions are defined the same way as C++.
    • The only difference between the C++ and Java function here is the string class (which is capitalized in Java) and the naming convention (camel case instead of underscores).

Return Statements

You probably noticed that each function ends with a return statement. This is a statement specified by the return keyword and followed by a return value. Essentially, functions can be thought of as their return value.

So, you can think of:   sort_clothes ("blue")
as:                                "colors"

  • Once the function is called it is replaced with the return value.
  • Because functions are replaced with their return value, you can set a variable equal to a function call:

    String pile = sortClothes("red");
    System.out.println(pile);                    // should output "colors" to the console
  • Functions can only return one value at a time. If you're trying to return more than one thing, you probably need more than one function.
  • The only time you don't need a return statement is when a function's return type is void. The void return type can be used when you want to permanently modify the parameter sent in, or if you don't need to return a value.

    void print_message (string message)
    {
        cout << message << endl;             // should output the contents of message to the console
    }

Function Overloading

Function overloading is the defining of more than one function that have the same name, but different parameters. The parameters can vary by type or number. For example:

    int volume (int side)
    {
        cube_volume = side * side * side;
        return cube_volume;
    }

    int volume (int length, int width, int height)
    {
        rec_prism_volume = length * width * height;
        return rec_prism_volume;
    }

Both of these have the same name, volume. But for a cube you just need one parameter, whereas for a rectangular prism you need three parameters. There could be another function of the same name that uses a different definition of volume:

    int volume (char title)
    {
        if (title == "A" || "a")
            return 1;

        else if (title == "B" || "b")
            return 2;

        // etc to Z
    }

In this case we still return an integer, but this corresponds to which volume an encyclopedia reference book is. 

It is important to note that function overloading is dependent on parameters NOT the return type. The compiler doesn't know or care what the return type is when it is compiling. But it does look at the parameters.

Also, parameter overloading is found in both C++ and Java, but not officially in Python.

No comments:

Post a Comment