Home > Articles > Programming > Ruby

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))) {
      ++freqs[word];
    }
  }
  // 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:

sort!(compile_time_arguments)(run_time_arguments);

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020