Pascal features you can fall in love with

I am a bit sentimental I admit it. For years and years and years I've been writing and teaching Pascal, Pascal OOP and Delphi (not since 1999 though). Ever since the early days I had a certain fondness ofn the Pascal enumerated types and the Ord() function.

The Ord function returns a cardinal number (integer) for any given ordinal type. Ordinal Types are cardinal numbers like byte, integer, shortint etc., chars (!) and enumerated types. So Ord(0) = 0, and Ord('@') = 64 as 64 is the ASCII code of the '@' char in the order of the ASCII characters. Nice.

In the same category as Ord(), are the functions Pred(), Succ() and procedures Inc() and Dec(), which increase and decrease ordinal numbers. Things like Inc ('A', 32) is a valid thing in Pascal, and increases the ordinal value of 'A' by 32, making it an 'a'. Thus making the nicest of capitalisation routines that you can find in any computer language:
if (c in ['A'..'Z']) then // convert char c to lower case
Inc(c, 32);

Digressing. The reason I've written this post was to talk about enumerated types. Consider:
TTile = (tlSpace, tlWall, tlBrick, tlDoor, tlLeft, tlRight, tlUp, tlDown, tlLeftLocked, tlRightLocked, tlUpLocked, tlDownLocked);

With the declaration above, Ord(tlSpace) = 0 and Ord(tlLeft) = 4. I needed a way to toggle the "lock" of a tile, all tiles being lockable except tlSpace..tlDoor. The answer?
case Ord(f_board[i]) of
4..7 : Inc (f_board[i], 4);
8..11 : Dec (f_board[i], 4);
That's it. If the order is between 4-7 increase the order by 4, if it's 8-11 decrease it. You could also write this for even better readability:
case f_board[i] of
tlLeft..tlDown : Inc (f_board[i], 4);
tlLeftLocked..tlDownLocked : Dec (f_board[i], 4);
Now, you can comment that this is not safe enough when changing the order of the enum, or moving enums around, but with a nice Unit test you won't be disappointed. One of the nicest things in Pascal is the declaration of sets with the double dot operator '..' and the inclusion of sets which the compiler converts to a bit operation. It's really cool and fast.


Popular posts from this blog

Useful Fonts for Linux

Chrome Packaged Apps

CyLog Raster Fonts for Linux