Tech Tuesday: Functions (Part 1)

In the last two posts we looked at control structures as part of the programming series here on Tech Tuesdays.  We saw that loops let us repeat a sequence of instructions, which is one way of having to avoid writing the same code over and over again.  Today we will learn about another and more powerful technique: the definition of new words that can then be used anywhere in the program.  You may recall the example of nautical terms from the post on programming languages:

For instance, if I tell another sailor to “jump the main halyard” they will know exactly what to do because this is an expression with a precise meaning.  I could of course also have given a lengthy description using general purpose instead of nautical English by saying something like “find the rope that runs from the top of the big sail to the top of the mast and then back down and then pull on it by jumping up and letting your weight help you.”

Learning the nautical terms once means that now every time you hear the term you have access to the sequence of steps for which it stands.  In programming we do this by defining a new word that becomes part of the vocabulary available in that program (and potentially in other programs) going forward.

Let’s start with a simple example that we already encountered in the post on syntax.  Not every programming language has a built in way of calculating the so-called factorial of n, which is the product of every number from 1 up to and including n.  Here is a short piece of code that accomplishes this

var n = 5; // put the value of n for which you want the factorial here
var f = 1;
var i = 1;
while (i <= n) {
    f = f * i;
    i++;
}
alert(n + " factorial is " + f);

At the end of this code the variable f contains the value of the factorial of n.  Now it would be very inconvenient to have to write this code everywhere in our program where we want to calculate a factorial!  Instead, Javascript (and pretty much every other programming language) gives us a way to define a new word that can be used.  Here is how this goes:

function factorial (n) {
    var f = 1;
    var i = 1;
    while (i <= n) {
        f = f * i;
        i++;
    }
    return f;
}

alert(5 + " factorial is " + factorial(5));
alert(6 + " factorial is " + factorial(6));

Let’s see what is going on here.  The word “function” is a reserved word in Javascript that is used to define new words.  The new word we are defining is “factorial” which contains all the code for calculating a factorial.  We then use our newfound powers to calculate and display the factorials for 5 and for 6 (120 and 720 respectively).

Why is the reserved word for defining new words called “function”?  Because each new word in Javascript has the ability to take so-called “arguments” — here the n — and return a value — here the value of the factorial.  Functions in Javascript can have from zero to many arguments.  For instance here is a trivial function for calculating the length of the hypotenuse of a right triangle:

function hypotenuse (a, b) {
    return Math.sqrt(a * a + b * b);
}

alert("a = 3, b = 4, c = " + hypotenuse(3, 4));

In Javascript every function can only return a single result.  That’s true for many but not all programming languages.  For instance in Go, functions can return multiple values. As it turns out returning only a single result isn’t as much of a limitation as it might seem at first.  We will learn about the reason in upcoming posts when we learn about how to create more complex data types that let us combine multiple values into a single “thing” that can then be returned.

Being able to define new words that we can add to the language is really essential to programming.  We can revisit most of the outline I first provided in my overview post and see how functions fit into them

1. Programming languages.  This is where I first mentioned the idea that “creating ever more powerful words” is a good way to think about programming.  All higher level language therefore have this ability to define new words.  Most languages use some form of function with a return value, but some languages also have “subroutines” that amount to a named piece of code that may or may not take arguments and has no return value.

2. Syntax. Just because we get to define new words does not mean we are allowed to change the syntax of the language that we are using.  In fact in most languages we can not change the syntax at all.  We can use the new word only where we could have previously used a variable, constant or literal value.  The function will be “called” and its returned value used in that place.  Some languages though have so-called macros which let us define new words that do in fact change the syntax of the language (to be covered when we get to advanced topics).

3. Semantics. Since this is the meaning of words, we are clearly changing the semantics of the programming language.  Again many languages only allow us to extend the semantics by adding new words.  But as we have seen some languages allow us to varying degrees to override the meaning of built-in words.  We saw examples of this using variables with the same name as built-in words.  Where a language permits that it may also permit redefining a built-in function.

4. Literals, constants and variables.  The arguments for a function in most programming languages set up new variables.  Next week’s post will be all about these arguments and how they work.

5. Data types. In some languages (but far from all), functions are a first-class data type. That is to say a variable can have a function as its value.  And in those languages functions can return other functions.  We will see how that can be useful when we get to more advanced topics.  There is another way that functions interact with data types.  An upcoming post will cover composite data types that allow us to hold together a bunch of different things.  For instance, we might want to have a data type “door” that allows us to specify how big the door is, what material it is made from, which key unlocks it, where it is located, etc.  Now in that case we might also have a bunch of functions that operate on doors.  Many higher level languages provide special features for associating functions with data types which we will explore in the future.

6. Control Structures.  Functions can also be seen as a third form of control structure (in addition to branches and loops).  Whenever a function is encountered, the flow of control, ie. the steps of the program that are executed, passes from where the function appears to the code inside the function itself.  As we will see in next week’s post there is more to this because functions act like blocks an have their own scope.

In next week’s post we will look more closely at how arguments work.  I promise that if you stick with these posts you will learn how we can get to writing code that actually does something like the following example from the first control structures post: while (is_locked(door)) turn(key, door);

Posted: 31st July 2012Comments
Tags:  tech tuesday programming functions

Newer posts

Older posts

blog comments powered by Disqus
  1. continuations posted this

Newer posts

Older posts