Create a Dictionary From a List of Pairs

· Jun 10, 07:05 AM

The Pair class and a Pair operator crept silently into the REALbasic language in REALbasic 2008r2. A Pair is an immutable object consisting of a pair of Variants. You create a Pair object using the : operator.

  dim p as Pair = 3:5

You retrieve the elements of a Pair using the (computed) properties Left as Variant and Right as Variant.

I am not sure why Real Software added Pairs to the language — perhaps it was a parting gift from Mars Saxman — but they are quite handy when one wants a lightweight way to group two objects together. For example, I’ve used them in a web server to queue pairs of HTTPRequest objects and the sockets on which they were received for later processing.

And now, just a year later, I’ve discovered that the Dictionary class gained a constructor at the same time.

  Sub Constructor(paramarray entries() as Pair)

This allows you to create a Dictionary object as follows.

  dim d as new Dictionary("foo":"bar", "x":"y")

For Dictionaries with a few items, I much prefer this to

  dim d as new Dictionary
  d.Value("foo") = "bar"
  d.Value("x") = "y"

In the course of this, I also stumbled on a syntactic quirk: in a method declaration, both

  paramarray entries() as Pair

and

  paramarray entries as Pair

are legal. I’ve no idea whether this is intentional; the language reference entry for ParamArray is inconsistent on this point.

---

Comment

  1. Amazing find! I’ve been using Pairs for a while already and had wished for better integration with Dictionaries.

    Thomas Tempelmann · Jun 10, 12:09 PM · #

  2. Pairs came about as the precursor to pass-by-name functionality. So you could do something along the lines of:

    DrawString( str:“The string to draw”, x:12, y:14 )

    As for the integration with dictionary, I think that came the release after Pairs came out — it wasn’t stealth so much as under-trumpeted.

    Aaron Ballman · Jun 10, 07:27 PM · #

  3. Well, isn’t that a coincidence? I got onto this in the course of rewriting my TemplateString class to use just this syntax to simulate named parameters.

    charles · Jun 10, 08:43 PM · #

Commenting is closed for this article.