Skip to content
Science

Programming for all, part 2: From concept to code

Computer programming is all about solving problems.

Matt Ford – | 124
Credit: Aurich Lawson
Credit: Aurich Lawson
Story text

Do one thing, and do it well

In our first installment, we wrote several programs that really did nothing more than illustrate a concept. Let’s turn the complexity up a notch and compose a program that actually solves a problem. The problem we are tasked with: given the high temperature of the past three days, compute the average and standard deviation.

To do this, we are going to need to implement an algorithm, the programming equivalent to a set of directions. It gives the major steps that one must take in order to solve a problem, but the details of how are left up to the programmer who implements the algorithm. For our problem at hand, we could write out our algorithm as follows:

  1. Read in three values
  2. Compute the sum of these values
  3. Compute the average by dividing the sum by 3.
  4. Figure out how far each value is from the average.
  5. Add the square of the distances obtained in step four
  6. Take the square root of the value in step five
  7. Divide by the square root of 3

So, let us set out to implement our remedial algorithm in MHF:

PROGRAM weatherStation
    NUMBER temperature1    # tell the computer that we're going to need
    NUMBER temperature2    # space set aside for the three temperatures
    NUMBER temperature3    # plus space for the average and standard
    NUMBER averageTemp     # deviation results
    NUMBER stddevTemp
    NUMBER sum, sqDist1, sqDist2, sqDist3 # we can define multiple 
                                          # variables of the same type 
                                          # on one line
    READ temperature1      # interface with someone or something
    READ temperature2      # to get our three temperature readings
    READ temperature3      # algorithm step 1

    # algorithm step 2
    sum = temperature1 + temperature2 + temperature3  
    # algorithm step 3
    averageTemp = sum / 3.0   
    # steps 4 and half of 5 from the algorithm
    sqDist1 = (temperature1 - averageTemp)^2
    sqDist2 = (temperature2 - averageTemp)^2
    sqDist3 = (temperature3 - averageTemp)^2  
    # other half of 5 and step 6 from the algorithm
    stddevTemp = ((sqDist1+sqDist2+sqDist3)/3.0)^(0.5) 

    PRINT "Average temperature = ", averageTemp, "+/-", stddevTemp
END PROGRAM weatherStation

The weatherStation program follows the algorithm laid out above and calculates the average and the standard deviation of three temperature readings. But it’s not possible to directly map the steps of the algorithm to the code. Some steps are split over multiple lines; other lines do more than a single step.

This example is reminiscent of real world development—as programs grow in complexity and size, it can be harder to track what individual steps are meant to accomplish.

To make the code easier to follow, and to allow the same operation to be done at multiple locations in the code, it’s often useful to compartmentalize your code. All major programming languages (that I am aware of) support what are called functions, methods, or subroutines. These allow programmers to pull out related operations and place them in their own module, where they are separated from other parts of the program.

Functions, as we’ll call them in our toy language, can be thought of like a mini-program within a program. They allow developers to isolate pieces of logic or complex operations and then refer to them by name later in the development cycle. In our weatherStation example, we could create one function for computing the average and another for computing the standard deviation.

One principle that drives developers is that each logical block of code should do one thing, and do it well—ideally without affecting things outside of its scope. Functions enable this to happen. Many programmers create collections of side-effect free functions; those that do what they are purported to do and nothing more. So a function to compute the average of three values would not format your hard drive, or order a pizza for you, or other less nefarious things (such as change the numbers themselves).

Let’s take a look at how we could rework weatherStation to modularize some of its functionality. We see that there are three key things that occur in this program: we read in some values, calculate the average, and calculate the standard deviation. The latter two can easily be rolled into stand-alone functions.

A function in MHF will look a lot like a little program, it will start with the keyword FUNCTION, followed by the name of the function, then a parenthetical list of the inputs to the function. (These inputs are formally known as the arguments.) Finally, a function will contain a RETURNS keyword, which identifies any value that gets sent back when the function is complete. Let’s look at a modularized weatherStation program

PROGRAM modularWeatherStation
    NUMBER temperature1    # tell the computer that we are going to need
    NUMBER temperature2    # space set aside for the three temperatures
    NUMBER temperature3    # plus space for the average and standard
    NUMBER averageTemp     # deviation results.  Just like before
    NUMBER stddevTemp

    READ temperature1
    READ temperature2
    READ temperature3

    # we will call a function that computes the average for us
    # at this line, control of the program will be transferred 
    # to the computeAverage function
    averageTemp = computeAverage( temperature1, temperature2, temperature3)

    # likewise for the standard deviation
    stddevTemp = standardDeviation( temperature1, temperature2, temperature3, averageTemp)

    PRINT "Average temperature = ", averageTemp, "+/-", stddevTemp
END PROGRAM weatherStationRefactor

FUNCTION computeAverage( NUMBER n1, NUMBER n2, NUMBER n3) RETURNS NUMBER
    NUMBER sum
    # the values passed into this function will be mapped to
    # the values n1, n2, and n3--only in this function
    sum = n1 + n2 + n3
    # at a RETURN statement, the program will return to the 
    # point where it left off
    RETURN sum/3.0 
END FUNCTION computeAverage

FUNCTION standardDeviation( NUMBER n1, NUMBER n2, NUMBER n3, NUMBER avg) RETURNS NUMBER
    NUMBER sqDist1, sqDist2, sqDist3

    sqDist1 = (n1-avg)^2
    sqDist2 = (n2-avg)^2
    sqDist3 = (n3-avg)^2

    RETURN ((sqDist1+sqDist2+sqDist3)/3.0)^(0.5)
END FUNCTION standardDeviation

Program modularWeatherStation will produce the same results as our previous weatherStation program (assuming we give it the same three inputs). However, the ideas and implementation of the average and standard deviation are encapsulated in a function. The consumer of these functions—the main program—doesn’t care what happens in the functions, as long as it gets the average back.

When the main program begins, it will set aside space for all the variables we tell it we will need then it will read in the three temperatures that we are interested in. When we reach line 15, we call the function computeAverage with the arguments temperature1, temperature2, and temperature3. Once the computer reaches this line of the main program, it will transfer its control to the computeAverage function, which is defined later.

In computeAverage, temperature1, temperature2, and temperature3 are now referred to by their local aliases, n1, n2, and n3. We define a local variable— variable that will only exist as long as the execution of the program is within the computeAverage function—for the sum. The algorithm for computing the average is carried out as before. Before we reach the final line in the computeAverage function, however, we encounter a RETURN statement.

On the line where we first describe the function, we also noted that it would return a NUMBER-type variable. In this case, the RETURN statement contains an expression that evaluates to a NUMBER-type variable. That value gets returned to the point in the main body of the program where the function call was made. The program will then continue to run from that point on as before.

Listing to one side

Our recent forays into weather work have relied on the fact that we will have three temperature readings, no more, and no less. How are we to proceed if we wish to look at four temperature readings? The easy answer would be to declare a fourth NUMBER variable and modify the calls to computeAverage and standardDeviation to take four numbers. This will work, until the day we are told that we now need five, or six, or more temperature readings. You could always keep adding more and more NUMBER variables to the program, but this will quickly become unwieldy.

To get around this issue, programming languages (at least every one I can think of) will have some sort of built-in container that can be used to hold an arbitrary number of one type of variable. In C, C++, Fortran, BASIC, Pascal, and a host of other languages, this is called an array. In Lisp, Scheme, F#, Haskell, and others, it is a list.

Both of these containers are similar: you can have multiple variables inside of a given one and they can all be passed around and referred to as a single variable. You can reference any individual item in the container using the appropriate notation. And finally, (in some of these languages) you can add or remove items at will.

In our toy language, we are going to take the best of all these worlds for our LIST type. So, in MHF if we wanted a list of numbers, we would declare the variable to be of the type NUMBER LIST. A list of characters would be a LETTER LIST, and so on. The elements in a LIST are unsorted and are added in the order in which we put them. One way to think of lists (or arrays in other languages) is like a big filing cabinet or a stack of drawers. We can always put another drawer on top, and each drawer can be opened to reveal a single thing that it is holding. We can count the number of drawers to know how many we have at any one time, and we can count up from the bottom (1st drawer) if we want to see what is in drawer number n.

There will be a couple of special functions that will be part of the language itself that deal with LISTs: ADDBEGIN and ADDEND. These will add an element (of the proper type) to an existing list. We’ll also have LENGTH, which will take a LIST and tell us how long it is (i.e. how many elements is holds).

A schematic of the NUMBER LIST that has a value of [1,2,3,4].
If we wish to examine the first element in a LIST, we would use the following syntax: listname[1]. If we wanted to look at the nth element in the list, we would examine it like listname[n]. We can also assign a value to any element in the same way we’d change a variable of that data type (list name[n] = x). Let’s look at a simple program that examines some operations on a LIST data type.

PROGRAM introToLists
    NUMBER index     # will be used to count in a loop
    NUMBER LIST myList
    NUMBER LIST squareList

    myList = [1,2,3,4,5,6] # Like we can set the value of a number, 
                           # we can set the value of a list using 
                           # [] and , to separate values
    # Print out myList
    FOR index = 1 TO LENGTH(myList) INCREMENTBY 1
        PRINT myList[index]
    END FOR   # this would display the numbers 1, 2, 3, 4, 5, and 6

    # populate squareList
    FOR index = 1 TO LENGTH(myList) INCREMENTBY 1
        # ADDEND takes a list, and a value that will fit into that 
        # list and puts it on the end of the list
        ADDEND(myList[index]^2, squareList)                                
    END FOR

    # Print out squareList
    FOR index = 1 TO LENGTH(squareList) INCREMENTBY 1
        PRINT squareList[index]
    END FOR # this would display 1, 4, 9, 16, 25, and 36

    # modify something in squareList
    squareList[5] = 27.39
    FOR index = 1 TO LENGTH(squareList) INCREMENTBY 1
        PRINT squareList[index]
    END FOR # this would now print 1, 4, 9, 16, 27.39, and 36
END PROGRAM introToLists

One thing that may not appear important in the above program is that we have called a few functions that have taken a LIST type as one of their arguments. This capability would allow us to extend our weatherStation program to be able to read arbitrarily large numbers of inputted temperatures and carry out the same operations as before. Let’s re-examine that problem, but this time we’ll use LIST types so that we are not restricted to only three entries.

PROGRAM listBasedWeatherStation
    NUMBER LIST temperatures
    NUMBER temp, averageTemp, stddevTemp
    LETTER continue # read in as many temperatures as the user wants!

    continue = Y
    WHILE( Y == continue) DO
        PRINT "Please input a temperature"
        READ temp
        # add the newest read in value to the list of temperatures
        ADDEND( temp, temperatures) 
        PRINT "Would you like to enter another value? [Y/N]"
        READ continue
    END DO 
    # At this point we have a list of temperatures,
    # we don't know how long it is, but we'd like to
    # find it average and standard deviation, just like before

    # We can pass a list to a function like any other data
    averageTemp = computeAverage( temperatures)  
    stddevTemp = standardDeviation( temperatures, averageTemp)

    PRINT "Average temperature = ", averageTemp, "+/-", stddevTemp
END PROGRAM listBasedWeatherStation

FUNCTION computeAverage( NUMBER LIST nums) RETURNS NUMBER
    NUMBER sum, index 
    sum = 0.0   # Make sure we start with nothing

    # add up all the elements in the list
    FOR index FROM 1 TO LENGTH(nums) INCREMENTBY 1
        sum = sum + nums[index]   
    END FOR
    # divide the sum by the number of elements
    RETURN sum/LENGTH(nums)       
END FUNCTION computeAverage

FUNCTION standardDeviation( NUMBER LIST nums, NUMBER avg) RETURNS NUMBER
    NUMBER sqDist, sum, index 
    sum = 0.0

    FOR index FROM 1 TO LENGTH( nums) INCREMENTBY 1
        sqDist = (nums[index]-avg)^2
        sum = sum + sqDist
    END FOR
    RETURN (sum/LENGTH( nums))^(0.5)
END FUNCTION standardDeviation

One thing to (re)note about our redone weather station program: since we modularized the calls to computeAverage and standardDeviation, the main routine does not need to care about how the work gets done under the hood, merely that it works when we give it the appropriate arguments. We are once again free to change how these functions perform their work as long as we don’t change what they expect as inputs and what they will return as outputs. (The format of the inputs and outputs is known as the function’s prototype.)

Calling ourselves out

In the previous section, we described lists as a chain of similarly typed variables grouped together. We could access them at will, add more values to them, and change the values they contained. But instead of thinking of a list as a chain of items, we can think of a list as being one of two things: an item of a specific type followed by a list or a special value that we will call NULL.

That’s turning the definition on its head a bit, but let’s think it through—this subtle change can open up some very powerful ways to think about storing data. If we look at any given element of a NUMBER LIST we are going to find either a NUMBER followed by a NUMBER LIST, or this special value NULL. NULL is a programming term that essentially means nothing.

This is called a recursive definition, because we are defining a list in terms of… a list. Not obvious, but once it clicks, it opens up some neat new tricks.

Similar to a recursive definition, we can also have what are termed recursive functions—functions that are defined in terms of themselves! These are sometimes easier to see in a mathematical framework; one of the simplest is the Fibonacci numbers.  The nth Fibonacci number is defined as the sum of the (n-1)th Fibonacci number plus the (n-2)th Fibonacci number; the first and second Fibonacci numbers are 0 and 1.

If we wanted to calculate the 5th Fibonacci number, we would proceed as follows:

Fib(5) = Fib(4) + Fib(3)

Well, we don’t know what the fourth or third Fibonacci numbers are, but we know that from the definition we can write:

    Fib(4) = Fib(3) + Fib(2)
    Fib(3) = Fib(2) + Fib(1)

Aha, we know what the 1st and 2nd Fibonacci numbers (Fib(1) and Fib(2)) are—they are zero and one. So we can plug them in

    Fib(3) = 1 + 0 = 1
    Fib(4) = 1 + 1 = 2

Okay, now we know the values for the third and fourth Fibonacci numbers, we can finally calculate the fifth one

Fib(5) = 1 + 2 = 3

And we now have our answer! Let’s look at creating a simple program that does this

PROGRAM Fibonacci
    NUMBER fibNumber, answer

    PRINT "Which Fibonacci number would you like to compute?"
    READ fibNumber answer = computeFibonacci( fibNumber)
    PRINT "Fibonacci number ", fibNumber, " is ", answer
END PROGRAM Fibonacci

FUNCTION computeFibonacci( NUMBER n) RETURNS NUMBER
    IF( n == 1) THEN # if we are asking for the first Fibonacci number
        RETURN 0     # 0 is the first Fibonacci number
    ELSE
        IF( n == 2) THEN
            RETURN 1 # 1 is the second Fibonacci number
        END IF
    END IF
    # If we are not asking for the first or second 
    # Fibonacci number, then we need to compute it
    RETURN computeFibonacci(n-1) + computeFibonacci(n-2)   # /Neo: Woah!
END FUNCTION computeFibonacci

Now, let’s look at how this concept can be applied to a LIST container using our new way of thinking. For the sake of argument, let’s say that our language has a few built-in functions for working with LISTs, namely HEAD which will take a list and tell us what the first element in the list is; and REST, which will again take a list but will now return the remainder of the list (i.e. the part of the list that follows our HEAD element). If we are at the end of the list, it will inform us that there is no more list remaining by returning NULL.

The key thing that these features allow is letting us move through the contents of a list without even knowing how many elements it contains. Let’s test this idea out by simply printing a list:

PROGRAM newPrintList
    NUMBER LIST myList
    myList = [1,4,9,13,72,34,81]  # some random list we wish to print
    # This function will return nothing, so we don’t 
    # need to set a variable to it
    newPrint( myList)
END PROGRAM newPrintList

FUNCTION newPrint( NUMBER LIST l) RETURNS NOTHING
    # here is where we will do all the work
    IF( l == NULL) THEN
        # If there is no list to print, we are done - simply return
        RETURN          
    END IF
    # If we reach here, there is obviously something in the list, so
    # Print out what the current head element in the list is
    PRINT HEAD(l)
    # Print out what is left in the list
    newPrint( REST( l)) 
    # since we return noting, then we only need a RETURN keyword here
    RETURN
END FUNCTION newPrint

This function, newPrint, utilizes our different definition of a LIST very effectively. We know that a list is either an element followed by a list, or NULL. newPrint checks to see if the list is null—if it is, there is obviously nothing to print out, so it simply returns. However, if the list is not NULL, then newPrint does the only thing it knows how to do: it prints the current element in the list, and calls newPrint (itself) with the remainder of the list! This method of thinking has allowed us to completely ignore how long the list is and has let us do a simple operation that works on one thing at a time.

Functions as arguments and returned values

So far in our discussion of functions, we’ve seen them take fairly routine data and likewise return equally routine data (NUMBERS, mostly). However, if we open ourselves and our language up to the possibility that our functions can take and return not only simple pieces of data, but other functions, then we can start doing some very interesting things. For instance, what if we wanted to apply a function to every element in a LIST? This type of operation is called map, and can be carried out as follows:

PROGRAM mapDemo
    NUMBER LIST numbers
    NUMBER LIST squares
    numbers = [1, 2, 3, 4, 5, 6]
    newPrint( numbers)  # Will print 1, 2, 3, 4, 5, 6
    squares = map( squareFunc, numbers)
    newPrint( squares)  # Will print 1, 4, 9, 16, 25, 36
END PROGRAM mapDemo

FUNCTION newPrint( NUMBER LIST l) RETURNS NOTHING
    IF( l == NULL) THEN
        RETURN
    ENDIF
    PRINT( HEAD(l))
    newPrint( REST(l))
    RETURN
END FUNCTION newPrint

FUNCTION squareFunc( NUMBER n) RETURNS NUMBER
    # This is a function that takes one number and returns it squared
    RETURN n*n
END FUNCTION squareFunc

# map takes as its first argument, a function, f, that
# takes a NUMBER as an argument and returns a NUMBER 
FUNCTION map( FUNCTION f(NUMBER) RETURNS NUMBER, NUMBER LIST l) RETURNS NUMBER LIST
    IF( NULL == l) THEN
        RETURN [] # If there is nothing left, return an empty list.
    END IF
    # Here we will grow our return list, by adding
    # the result of evaluating our function f with input
    # the current HEAD of the input list, to the result of
    # 'map'ping the function f to the REST of the list l.
    RETURN ADDBEGIN( f(HEAD(l)), map(f, REST(l)))  
END FUNCTION map

Clear as mud, yes? The map function works by using the language’s built-in ADDBEGIN function. ADDBEGIN, much like its sibling ADDEND, will add an element to a list. But instead of adding the element at the end of the list, this variant adds it to the beginning and appends the list to the element.

Each time through map, we start building a new list with ADDBEGIN, adding the result of running the current value of the list through the function we passed in (funcSquare in our example) to the result of map of the function to the REST of the list. Once the REST of map is empty (NULL), map will simply return the empty list []. Let’s break this out a bit and look at what happens with a simple list, namely [1, 2, 3]. The first time through the following call is made:

map( funcSquare, [1,2,3])

This will return the following:

RETURN ADDBEGIN( 1^2, map(funcSquare, [2,3]))

We don’t know what the result of this new call to map is, so we’ll make it. The second call to map becomes:

    map(funcSquare, [2,3])

which will result in:

    RETURN ADDBEGIN( 2^2, map(funcSquare, [3]))

The third call to map will be:

        map(funcSquare, [3])

In turn, this will have yet another call to map, but this result will contain the final call to map

        RETURN ADDBEGIN( 3^2, map(funcSquare, NULL))

The final call to map is then:

            map(funcSquare, NULL)

We know what the result of calling map with a NULL list is: it is just the empty list! So we’ll return that.

            RETURN []

Now that we have a concrete starting point, much like in the Fibonacci example, we can go back and fill in our unknown values:
Going back one level, results in:

        RETURN ADDBEGIN( 3^2, [])

This is of course, just the list [9]. Stepping back one level and filling in what we know gives:

    RETURN ADDBEGIN( 2^2, [9])

This is the list [4,9]. Finally getting back to the first call level we have:

RETURN ADDBEGIN( 1^2, [4,9])

Which can be evaluated to give our final result: the NUMBER LIST [1,4,9].

Before we finish up our jaunt through some introductory programming topics, let’s visit one last technique that finds uses all around the programming world. This is considered by some to be one of the most fundamental algorithms there is: the fold technique (PDF). This is a powerful technique that takes a list, an operation, and an initial value. It collapses the elements of that list down, carrying out the operation on the first element of the list and the initial value.

PROGRAM foldDemoSum
    NUMBER LIST myNums = [1,2,3,4,5]
    NUMBER sum
    # addTwo is a function that will simply add two numbers
    sum = fold(myNums, 0, addTwo)
    PRINT "The sum of myNums is ", sum
END PROGRAM foldDemoSum

FUNCTION addTwo( NUMBER m, NUMBER n) RETURNS NUMBER
    RETURN m+n
END FUNCTION addTwo

FUNCTION fold( NUMBER LIST l, NUMBER acc, FUNCTION f(NUMBER, NUMBER) RETURNS NUMBER) RETURNS NUMBER
    IF( NULL == l) THEN
        RETURN acc
    END IF
    RETURN f(HEAD(l), fold(REST(l), acc, f))
END FUNCTION

Again, isn’t that clear? Well, to new users, it is probably (almost certainly) difficult to see what is happening here, so let’s go through it step by step. We’ll use the list [1,2,3], a starting value of 0, and the function addTwo from above. Our first call will then look like this:

fold([1,2,3], 0, addTwo)

Once we get into the body of fold we will check to see if our list is NULL. It is not, so we will call our function with two arguments: the head of the list and the results of another fold on the remainder of the list. We will return:

RETURN addTwo( 1, fold([2,3], 0, addTwo))

But we can’t evaluate this, so we head back into fold a second time:

    fold([2,3], 0, addTwo)

This will return a statement that will contain yet another call to fold (since we still don’t have a concrete answer):

    RETURN addTwo(2, fold([3],0,addTwo))

We still can’t fully evaluate this, so we go down one more level, let’s examine our call to fold this time through:

        fold([3],0,addTwo)

Once again, we will have a return statement that will contain a call to fold:

        RETURN addTwo(3, fold(NULL,0,addTwo))

This contains our final call to fold

            fold(NULL, 0, addTwo)

Now that the list is NULL, we can evaluate this function exactly, and we return its value of the acc variable.  As of now, it is 0.

            RETURN 0

Moving up one level and substituting our known results lets us learn that

        RETURN addTwo(3,0)

This result is now obviously 3. Again, moving up one more level we learn that

    RETURN addTwo(2,3)

Again, this is simply seen to be 5. And once more for feeling, we get to our final result

RETURN addTwo(1,5)

Adding 1 and 5 will give the trivial answer of 6. With that, we find that we have the correct sum of one through three. If we were to write out the entire chain of return statements, we would see that what we really evaluated was the following:

RETURN addTwo(1, addTwo(2, addTwo(3, 0)))

This general approach pops up in a fair number of places when doing software development. It may not always look like this, but it is important to be aware of it—when you see it, you’ll know what is going on. Let’s take a step back and re-visit our weatherStation program with some of the new tricks of the trade that we have learned.

PROGRAM finalWeatherStation
    NUMBER LIST temperatures
    NUMBER temp, averageTemp, stddevTemp
    LETTER continue

    # read in as many temperatures as the user wants!
    continue = Y
    WHILE( Y == continue) DO
        PRINT "Please input a temperature"
        READ temp
        # add the newest read in value to the list of temperatures
        ADDEND( temp, temperatures) 
        PRINT "Would you like to enter another value? [Y/N]"
        READ continue
    END DO
    averageTemp = computeAverage( temperatures) 
    stddevTemp = standardDeviation( temperatures, averageTemp)
    PRINT "Average temperature = ", averageTemp, "+/-", stddevTemp
END PROGRAM finalWeatherStation

FUNCTION addTwo( NUMBER m, NUMBER n) RETURNS NUMBER
    RETURN m+n
END FUNCTION addTwo

FUNCTION sqDist( NUMBER x, NUMBER avg) RETURNS NUMBER
    RETURN (x-avg)^2
END FUNCTION

FUNCTION map( FUNCTION f(NUMBER) RETURNS NUMBER, NUMBER LIST l) RETURNS NUMBER LIST
    IF( NULL == l) THEN
        RETURN []
    END IF
    RETURN ADDBEGIN( f(HEAD(l)), map(f, REST(l)))
END FUNCTION map

FUNCTION fold( NUMBER LIST l, NUMBER acc, FUNCTION f(NUMBER, NUMBER) RETURNS NUMBER) RETURNS NUMBER
    IF( NULL == l) THEN
        RETURN acc
    END IF
    RETURN f(HEAD(l), fold(REST(l), acc, f))
END FUNCTION

FUNCTION computeAverage( NUMBER LIST nums) RETURNS NUMBER
    RETURN fold(nums, 0, addTwo)/LENGTH(nums)
END FUNCTION computeAverage

FUNCTION standardDeviation( NUMBER LIST nums, NUMBER avg) RETURNS NUMBER
    NUMBER LIST distSquared
    NUMBER tempSum
    # Create an auxiliary function that only takes 1 argument ('x')
    # and can be used with our map function.
    FUNCTION auxHelper(NUMBER x) RETURNS NUMBER = sqDist(x, avg) 

    distSquared = map( auxHelper, nums)   # this will hold the value 
                                          # of the square of the distance
                                          # between each entry and 
                                          # the average.
    tempSum = fold(distSquared, 0, addTwo)
    RETURN (tempSum/LENGTH(distSquared))^(0.5)
END FUNCTION standardDeviation

Whew, that was quite different from the first time through, wasn’t it? One thing to note though, is that the function standardDeviation and computeAverage completely encapsulate the manner in which they work! This means that as far as any program that uses the computeAverage and standardDeviation functions is concerned, how they work does not matter. The main portion of the program finalWeatherStation is exactly the same as the previous revision listBasedWeatherStation. All the differences are hidden away in the functions, the main program knows that by passing a NUMBER LIST to average and a NUMBER LIST and NUMBER to standardDeviation, that it will be given back the average and standard deviation of the list.

While finalWeatherStationhas a lot more functions than any of our previous revisions, but each function on its own is so trivial that we can be very confident it works as we expect it to, without errors. When you break a problem up into such small chunks and can guarantee that each piece works, you will have a much easier time concluding that the entire thing together is sound.

Conclusion

This article started with a brief introduction to what a computer *really* is—a bunch of dumb switches. Once we understood that, we showed how we could use these switches to do something productive: and if we change the way we count, then it becomes possible to express ideas with nothing but on/off switches. While the early days of computer programming quite literally required flipping switches in between the on/off state, we’ve grown past that. High level languages allow humans (programmers) to express complex ideas in a format that they can easily read and, with the help of a compiler, a computer can understand and carry out.

With that background, we’ve gone through a host of the techniques that are widely used within the programming world. I would argue that more than 99.9 percent of all the programs that currently exist use at least one of the concepts discussed here. While this article did not focus on an existing language, people looking to understand computer development need to understand that the specific language is not the most important part—the concepts and techniques are.

A computer language is just a language, a means for thoughts to be expressed. It is the thoughts and ideas that transcend the languages that are key to a computer programming. Once you have a good grasp of these basic ideas, they become easy to translate among existing languages.

Numerous computer languages have come and gone in the past 60 plus years, and countless more will follow. But the ideas that a developer wishes to express will not change (the hope is that languages of the future will make it easier to express them). Everything from operating systems or high-frequency trading algorithms rely on these ideas.

If you want to start computer programming keep in mind that it is about solving a problem. If the problem at hand is too big to solve in one go, break it down into smaller problems that are more tractable. If any of them is still too big to solve, break it down further and further until you end up with lots of little, easily solvable problems. Once you have solutions for all the little issues, putting them back together is considerably easier and a solution to the once intractable problem can emerge.

Programming is not some walled-off Ivory Tower where only the gray-bearded few may enter. It is open to anyone with a computer and an idea.

Further reading

  • Structure and Interpretation of Computer Programs
  • Fabulous Adventures in Coding
  • Lambda the Ultimate
  • How to Design Programs
  • Learn Python The Hard Way
  • Dive into Python
  • Project Euler

Listing image: Aurich Lawson

Photo of Matt Ford
Matt Ford Associate writer
Matt is a contributing writer at Ars Technica, focusing on physics, astronomy, chemistry, mathematics, and engineering. When he's not writing, he works on realtime models of large-scale engineering systems.
124 Comments