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.
Now, I need my function.
Or maybe I use a bit of syntactic sugar.
And then when I call it.
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").
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?
And in the functional programming language.
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. |