|
|
||||||||
|
||||||||
|
|
|
|||||||
|
Pairs Written by Aaron Ballman The concept of a pair is something that comes up frequently in programming. As REALbasic programmers, you're undoubtedly familiar with the Dictionary class. That's just a fancy way to store pairs of information -- keys and values. However, it doesn't afford you an easy way to describe a single key/value pair as its own entity. That's what makes the new Pair class a very interesting concept. Let's start out on the simple side of things and say you want to represent a key/value pair in your code. To create a pair the easy way, you can do this:
What this gives you is a single class whose Left value is 1, and Right value is 2. It's as easy as that! So let's take a more real-world example. Let's pick on serialization -- you want to represent a property, and its value in a generic fashion. Voila! Now you have an array of key/value pairs in a handy list. Let's say you wanted to write the data out to disk. You could do that with something like this (in CSV format): So it's a fancy way to deal with key/value pairs -- but that's not all you can do with it! It's also a very handy singly-linked list. Check it out: Dim p as Pair = 1 : 2 : 3 : 4 : 5In this example, you have a singly-linked list that traverses from 1 to 5. Laying it out with temps: Temp1: left = 1, right = Temp2 Temp2: left = 2, right = Temp3 Temp3: left = 3, right = Temp4 Temp4: left = 4, right = 5 But wait, there's more! It's not just a singly-linked list -- it can also represent a binary tree. Because there's a left and a right property, you can use the Pair class as a node in a tree with two possible children. Hopefully this gives you a few ideas as to how you can make use of the new Pair class, and it's corresponding operator (the colon) to clean up some of your projects. It's not the most ground-breaking feature ever, but it is a neat little tool to make use of. |
||||||||
| Copyright © 2008 REAL Software, Inc. | Site Map | Activation | Privacy | Contact |