Static vs dynamic typing: do what thou wilt

24Dec06

There has been a raging debate (just watch Reddit!) on static vs dynamic typing and programming language choice these days. Most participants seem honest enough to point out the advantages and disadvantages of each typing scheme — dynamic typing requires less grunt “typing” work but is significantly less “safe” than static typing — but don’t account for the flexibility of typing usage available to each language.

While from a strict definitional viewpoint static and dynamic typing are quite disjoint — type checking is either done at compile-time or left for runtime — there are quite a few intermediate schemes. Some languages (Visual Basic, IIRC) allow for Variant data types, for example; Haskell’s own take at this seems to be Data.Dynamic, but I don’t really know for sure.

There is, moreover, even in a language disallowing variant data types, a spectrum of typing strategies that runs from no-pasaran typeful programming to just exploiting cartesian products and sums from machine types. Say you want to represent pixels in an infinite-sized 2D display; let us explore some ways of specifying that.

Military typing:

Horizontal coordinates and vertical coordinates are really quite different types of information and should not ever be used in one single calculation. Therefore, we first have to define these coordinate types.

data XPos = XP Int
data YPos = YP Int

Now we can define a pixel as the cartesian product of these types:

data Pixel = Pixel XPos YPos

Writing functions for this rather indirect type will require somewhat messy pattern matching:

etc. If you wanted to do something strange like adding x and y coordinates, you’d have to go out of your way to define

wacky (XP x) (YP y) = (XP x+y)

You can’t even overload (+), since its type is

(+) :: (Num a) => a -> a -> a

and therefore we can’t add values of different data types even if we attempt to declare XP and YP as instances of Num. This is both a gift and a curse. What strong typing brings in to the table is that you can’t mess with the intuitive semantics of (+) — you can’t beat the proverbial wisdom to the effect that you can’t add apples and oranges. On the other hand, it’d sure be nice to have a general “lift” combinator that took functions from Ints and turned them on functions on XP or YP, etc — which you can’t, because such a function wouldn’t be typeable short of defining a WrappedInt class and doing away with the whole benefit of military typing. Instead, you have to live with

Military typing requires a Big Design Up Front. It also requires an army of programmers writing functions on coordinates and pixels. It helps enforce security, but is a major headache as well; if you’re not going to war, you might want to go with something weaker. A first “weakening” of the pixel specification is

What is lost here is that the compiler no longer knows that X-coordinates and Y-coordinates are different things. New, wide avenues for human error are opened, but we may often consider that the price tag of military typing is not worth the benefits — we want to trust our programmers and end-users at least a little bit.

Binder typing with tabs:

An interesting syntactic variation of binder typing is obtained through the use of a record. A record type is identical in functionality to the cartesian product type defined above (you can even use the same functions, without any rewriting), except in that it creates “destructor” functions automatically by act of declaration:

data Pixel = Pixel { hor :: Int, ver :: Int }

This allows us to rewrite the functions above (which, again, still work with this record type) in a different, possibly less messy fashion:

What has happened in effect is that the data declaration creates new functions hor :: Pixel -> Int and ver :: Pixel -> Int which can be used to break down the product type. In some cases, this makes the semantics of functions more transparent.

If we define a constructor function we might be able to bypass pattern-matching altogether:

point x y = Pixel x y
liftXY f = liftM2 point (f . hor) (f . ver)

All this, of course, is unnecessary if one’s willing to muck about with pattern-matching, and is only mentioned for the sake of ooh ahh.

Plain lattice typing:

In this modality, we do away with the data declarations, the special types and just use Haskell’s built-in tuple data type — like one would in pretty much any other programming language. Function definitions are soothingly familiar for the uninitiated:

up (x,y) = (x, y+1)
addpos (x,y) (x', y') = (x+x', y+y')

Lifts are easy to define as well, and will apply not only to our pixels, but to any pair of numbers — say, height and weight of a person.

liftXY f (x,y) = (f x, f y)

An alternate, wizardly version of this, suggested on the irc channel is

liftXY = join (***)

Given that we haven’t declared any typing, this is “almost” dynamic typing! That is, Haskell is still “static” in the sense that any machine type clashes (for example, trying to add a string to an integer) will prevent compilation, but we’re no longer doing any type work.

Most of the time, stronger typing than the last example will be employed. That can be annoying, at times. I used to do graphics with a homespun library that produced pixel matrices (actually, nested lists of lists) that would later be exported into a PPM image file. When I began using OpenGL, none of my functions would work, because Haskell’s OpenGL lib uses binder typing (pixels have types like Vertex4 GLFloat GLFloat GLFloat GLFloat); similar complaints have been on the rise inside the Haskell community itself; some people find they rewrite function logic because of incompatible typing models when moving from one project to the next, and building a coherent type model does require some Big Design Up Front.

Part of this is an artifact of data constructors and functions being different entities; often, adding constructor and destructor functions aids the fluidity of app logic between typing models, as we have seen. In any case, we’ve seen from the examples above that it’s often simpler to do quick hacks that are bound only to machine types rather than Big Design Up Front.

Bottom-up programming in Haskell need not be a matter of algebraic clarividence, particularly if you’re willing to give up some safety.

Recent Posts

Dr. Syntaxfree

Dr. Syntaxfree has no PhD and shouldn't call himself a "doctor", but does so for amusement value anyway. An unemployed (ok, graduate student) econopundit by day, he's been progressively obsessed about Haskell to the point he often can't fathom not working on it. A jack-of-many-trades, he has an unusual CS background in that he knows no imperative programming at all, he hopes to be both helpful to those less knowledgeable than him and illustrative to the really smart people trying to understand the mentality of a common man trying to tackle functional programming.

Licenses

All rights reserved for textual content. A specific exception is granted to wikis hosted in the haskell.org domain; any text or code can be freely copied to such pages. All code is otherwise released under the LGPL.