Home > Articles > Programming > Ruby

  • Print
  • + Share This
From the book

1.4 Arrays and Associative Arrays

Arrays and associative arrays (the latter colloquially referred to as hashtables or hashes) are arguably the most used compound data structures in the history of computing, enviously followed by Lisp's lists. A lot of useful programs need no more than some sort of array and associative array, so it's about time to see how D implements them.

Building a Vocabulary

For example, let's write a simple program following the specification:

  • Read a text consisting of words separated by whitespace, and associate a unique number with each distinct word. Output lines of the form ID word.

This little script can be quite useful if you want to do some text processing; once you have built a vocabulary, you only need to manipulate numbers (cheaper), not full-fledged words. A possible approach to building such a vocabulary is to accumulate already-seen words in a sort of a dictionary that maps words to integers. When adding a new mapping we only need to make sure the integer is unique (a solid option is to just use the current length of the dictionary, resulting in the IDs 0, 1, 2. . . ). Let's see how we can do that in D.

import std.stdio, std.string;

void main() {
   uint[string] dic;
   foreach (line; stdin.byLine) {
      // Break sentence into words
      string[] words = split(strip(line));
      // Add each word in the sentence to the vocabulary
      foreach (word; words) {
         if (word in dic) continue; // nothing to do
         uint newID = dic.length;
         dic[word] = newID;
         writeln(newID, '\t', word);

In D, the type of an associative array (a hashtable) that maps values of type K to values of type V is denoted as V[K]. So the variable dic of type uint[string] maps strings to unsigned integers—just what we needed to store word-to-ID mappings. The expression word in dic is true if the key word could be found in associative array dic. Finally, insertion in the dictionary is done with dic[word] = newID.

The variable words is an example of an array in action. Dynamically-sized arrays of T are denoted as T[] and are allocated in a number of ways, such as:

int[] a = new int[20]; // 20 zero-initialized integers
int[] b = [ 1,  2, 3 ]; // an array containing 1, 2, and 3

Our little utility doesn't need to allocate words because split takes care of that. Unlike C arrays, D arrays know their own length, accessible as arr.length for any array arr. Assigning to arr.length reallocates the array. Array accesses are bounds checked; code that enjoys risking buffer overruns can scare the pointer out of the array (by using arr.ptr) and then use unchecked pointer arithmetic. Also, a compiler option disables bounds checking if you really need everything that silicon wafer could give. This places the path of least resistance on the right side of safety: code is safe by default and can be made a tad faster with more work. Besides, many D idioms naturally obviate the need for bounds checking. For example, here's how to iterate over an array using a new form of the already-familiar foreach statement:

int[] arr = new int[20];
foreach (elem; arr) {
   /* ... use elem ... */

The loop above binds elem to each element of arr in turn, and there's never a need to check bounds (even if you do reallocate arr inside the loop, for a subtle reason that we'll discuss in Chapter ??). Assigning to elem does not assign back to elements in arr. To change the array, just use the ref keyword:

// Zero all elements of arr
foreach (ref elem; arr) {
   elem = 0;

And now that we got to how foreach works with arrays, let's mention one more useful thing. If you also need the index of the array element while you're iterating, foreach can do that for you:

int[] months = new int[12];
foreach (i, ref e; months) {
   e = i + 1;

The code above creates an array containing 1, 2,. . . , 12. The loop is equivalent to the slightly more verbose code below:

foreach (i; 0 .. months.length) {
   months[i] = i + 1;

D also offers statically-sized arrays denoted as e.g. T[5]. Outside a few specialized applications, dynamically-sized arrays are to be preferred because more often than not you don't know the size of the array in advance.

Arrays have shallow copy semantics, meaning that copying an array variable to another does not copy the entire array, just spawns a new view to the same underlying storage. If you do want to obtain a copy, just use the dup property of the array:

int[] a = new int[100];
int[] b = a;
++b[10];    // b[10] is now 1, as is a[10]
b = a.dup;  // copy a entirely into b
++b[10];    // b[10] is now 2, a[10] stays 1

Array Slicing. Type-Generic Functions. Unit Tests

Array slicing is a powerful feature that allows referring to a portion of an array without actually creating a new one. To exemplify, let's write a function binarySearch implementing the eponymous algorithm: given a sorted array and a value, binarySearch quickly returns a Boolean value telling whether the value is in the array. D's standard library offers a function doing that in a more general way and returning something more informative than just a Boolean, but that needs to wait for more language features. Let us, however, bump our ambitions up just a notch, by setting to write a binarySearch that works not only with arrays of integers, but with arrays of any type as long as values of that type can be compared with '<'. It turns out that that's not much of a stretch. Here's what a generic binarySearch looks like:

import std.array;

bool binarySearch(T)(T[] input, T value) {
   while (!input.empty) {
      auto i = input.length / 2;
      auto mid = input[i];
      if (mid > value) input = input[0 .. i];
      else if (mid < value) input = input[i + 1 .. $];
      else return true;
   return false;

unittest {
   assert(binarySearch([ 1, 3, 6, 7, 9, 15 ], 6));
   assert(!binarySearch([ 1, 3, 6, 7, 9, 15 ], 5));

The (T) notation in binarySearch's signature introduces a type parameter T. The type parameter can then be used in the regular parameter list of the function. When called, binarySearch will deduce T from the actual arguments received. If you want to explicitly specify T (for example for double-checking purposes), you may write:

assert(binarySearch!(int)([ 1, 3, 6, 7, 9, 15 ], 6));

which reveals that a generic function can be invoked with two pairs of parenthesized arguments. First come the compile-time arguments enclosed in !(...), and then come the run-time arguments enclosed in (...). Either or both sets of parentheses may be missing. Mixing the two realms together has been considered, but experimentation has shown that such a uniformization creates more trouble than it eliminates.

If you are familiar with similar facilities in Java, C#, or C++, you certainly noticed that D made a definite departure from these languages' use of angle brackets '<' and '>' to specify compile-time arguments. This was a deliberate decision aimed at avoiding the crippling costs revealed by experience with C++, such as increased parsing difficulties, a hecatomb of special rules and arbitrary tie-breakers, and obscure syntax to effect user-directed disambiguation.2 The difficulty stems from the fact that '<' and '>' are at their heart comparison operators,3 which makes it very ambiguous to use them as delimiters when expressions are allowed inside those delimiters. Such wannabe delimiters simply don't pair. Java and C# have an easier time exactly because they do not allow expressions inside '<' and '>', but that limits their future extensibility for the sake of a doubtful benefit. D does allow expressions as compile-time arguments, and chose to simplify the life of both human and compiler by extending the traditional unary operator '!' to binary uses and using the classic parentheses (which (I'm sure) you always pair properly).

Another detail of interest in binarySearch's implementation is the use of auto to leverage type deduction: i and mid have their types deduced from their initialization expressions.

In keeping with good programming practices, binarySearch is accompanied by a unit test. Unit tests are introduced as blocks prefixed with the unittest keyword (a file can contain as many unittests as needed, and you know how it's like—too many are almost enough). To run unit test before main is entered, pass the the -unittest flag to the compiler. Although unittest looks like a small feature, it is very handy for observing good programming techniques by making it so easy to insert small tests, it's embarrassing not to. Also, if you're a top-level thinker who prefers to see the unittest first and the implementation second, feel free to move unittest before binarySearch; in D, the semantics of a module-level symbol never depends on its relative ordering with others.

The slice expression input[a .. b] returns a slice of input from index a up to, and excluding, index b. If a == b, an empty slice is produced (and if a > b, an exception is thrown). A slice does not trigger a dynamic memory allocation; it's just an alias for a part of the array. Inside an index expression or a slice expression, $ stands in for the length of the array being accessed; for example, input[0 .. $] is exactly the same thing as input.

Again, although it might seem that binarySearch does a lot of array shuffling, no array is newly allocated; all of input's slices share space with the original input. The implementation is in no way less efficient than a traditional one maintaining indices, but is arguably easier to understand because it manipulates less state.

Counting Frequencies. Lambda Functions

Let's set out for another useful program: counting distinct words in a text. Want to know what were the most frequently used words in Hamlet? You're in the right place.

This program deals in associative array mapping strings to uints, and has a structure similar to the vocabulary building example. Adding a simple printing loop completes a useful frequency counting program:

import std.stdio, std.string;

void main() {
  // compute counts
  uint[string] freqs;
  foreach (line; stdin.byLine) {
    foreach (word; splitter(strip(line))) {
  // print counts
  foreach (key, value; freqs) {
    writefln("%6u\t%s", value, key);

All right, now after downloading hamlet.txt off the Net, which is to be found (at the time of this writing) at http://www.cs.uni.edu/~schafer/courses/051/assign/labs/lab12/hamlet.txt, running our little program against The Bard's chef d'oeuvre prints:

1 outface
1 come?
1 blanket,
1 operant
1 reckon
2 liest
1 Unhand
1 dear,
1 parley.
1 share.

which sadly reveals that output doesn't come quite ordered, and that whichever words come first are not quite the most frequent. This isn't surprising; in order to implements their primitives as fast as possible, associative arrays are allowed to store them internally in any order.

In order to sort output with the most frequent words first, you can just pipe the program's output to sort -nr (sort numerically and reversed), but that's in a way cheating. To integrate sorting into the program, let's replace the last loop with the following code:

// print counts
string[] words = array(freqs.keys);
sort!((a, b) { return freqs[a] > freqs[b]; })(words);
foreach (word; words) {
  writefln("%6u\t%s", freqs[word], word);

The function array takes the keys of the freqs associative arrays and puts them in array format, yielding an array of strings. The array is newly allocated, which is necessary because we need to shuffle the strings. We now get to the code:

sort!((a, b) { return freqs[a] > freqs[b]; })(words);

which features the pattern we've already seen:


Peeling off one layer of parentheses off !(...), we reach this notation, which looks like an incomplete and anonymous function:

(a, b) { return freqs[a] > freqs[b]; }

This is a lambda function—a short anonymous function that is usually meant to be passed to other functions. Lambda functions are so useful in so many places, D did its best at eliminating unnecessary syntactic baggage from defining a lambda: parameter types as well as the return type are deduced. This makes a lot of sense because the body of the lambda function is by definition right there for the writer, the reader, and the compiler to see, so there is no room for misunderstandings and no breakage of modularity principles.

There is one rather subtle detail to mention about the lambda function defined in this example. The lambda function accesses the freqs variable which is local to main, i.e. is not a global or a static. This is unlike C and more like Lisp, and makes for very powerful lambdas. Although traditionally such power comes at a runtime cost (by requiring indirect function calls), D guarantees no indirect calls (and consequently full opportunities for inlining) through a unique feature called local instantiation, which we'll discuss in Chapter ??.

The modified program outputs:

929 the
680 and
625 of
608 to
523 I
453 a
444 my
382 in
361 you
358 Ham.

which is as expected, with commonly used words being the most frequent, with the exception of "Ham." That's not to indicate a strong culinary preference of Dramatis Personae, it's just the prefix of all of Hamlet's lines. So apparently he has some point to make 358 times throughout, more than anyone else. If you browse down the list, you'll see that the next speaker is the king with only 116 lines—less than a third of Hamlet's. And at 58 lines, Ophelia is downright taciturn.

  • + Share This
  • 🔖 Save To Your Account