Computer Science Canada

What does functional programming get you? Aggregate datatypes

Author:  wtd [ Sun Feb 03, 2008 1:58 am ]
Post subject:  What does functional programming get you? Aggregate datatypes

Programs deal with data. In many cases they deal with aggregate data. That is to say, a single piece of data made up of smaller pieces of data. And of course they also deal with actions on that data.

The most common aggregate data structure people are acquainted with are arrays. They are the first such structures covered in many courses, and as such one of the ones programmers feel most at home with. As such they get used a lot. Even when it's not necessarily appropriate. Arrays are always homoegeneous. They always contain data of the same type. Of course, in dynamically-typed object-oriented languages "the same type" may be a very loose restriction.

Where things get more interesting is when we consider heterogeneous aggregate data structures. Here is where functional programming (or languages inspired heavily by fucntional programming) can offer a significant advantage.

Consider any of C, C++, Java, Pascal, etc. Every heterogeneous aggregate data structure needs a name. Let's say I want to return a point consisting of an x,y pair from a function. Well (assuming my standard library lacks this type) I need to define a Point datatype.

code:
typedef struct point {
    int x;
    int y;
} point_t;


Now, I need my function.

code:
point_t simple_point()
{
    point_t p;

    p.x = 2;
    p.y = 3;

    return p;
}


Or maybe I use a bit of syntactic sugar.

code:
point_t simple_point()
{
    point_t p = { 2, 3 };

    return p;
}


And then when I call it.

code:
int main()
{
    point_t p = simple_point();

    printf("%d, %d\n", p.x, p.y);

    return 0;
}


Now, this seems pretty straightforward, but let's see what this can become when we introduce type-inferencing, pattern-matching and a generic syntax for tuples (or "product types").

code:
let simple_point () = (2, 3)

let (x, y) = simple_point () in
    printf "%d, %d\n" x y


There's no declaration for the data type. But, don't I need that if I want to pass that data type to a function?

code:
typedef struct point {
    int x;
    int y;
} point_t;

void print_point(point_t p)
{
    printf("%d, %d\n", p.x, p.y);
}

int main()
{
    print_point(simple_point());

    return 0;
}


And in the functional programming language.

code:
let simple_point () = (2, 3)

let print_point (x, y) =
    printf "%d, %d\n" x y;;

print_point (simple_point ())


I leave it to the reader to decide if this is a good thing or not, but hopefully you'll do some experimenting beyond my silly, contrived examples.


: