#MonthOfJulia Day 23: Data Structures
Although Julia has integrated support for various data structures (arrays, tuples, dictionaries, sets), it doesn’t exhaust the full gamut of ptions. More exotic structures (like queues and deques, stacks, counters, heaps, tries and variations on sets and dictionaries) are implemented in the DataStructures package.
As always we start by loading the required package.
I won’t attempt to illustrate all structures offered by the package (that would make for an absurdly dull post), but focus instead on queues and counters. The remaining types are self-explanatory and well illustrated in the package documentation.
Let’s start off with a queue. The data type being queued must be specified at instantiation. We’ll make a queue which can hold items of
Any type. Can’t get more general than that.
The rules of a queue are such that new items are always added to the back. Adding items is done with
The queue now holds five items. We can take a look at the items at the front and back of the queue using
back(). Note that indexing does not work on a queue (that would violate the principles of queuing!).
counter() function returns an
Accumulator object, which is used to assemble item counts.
Using a Noah’s Ark example we’ll count the instances of different types of domestic animals.
Let’s see what the counter looks like now.
We can return (and remove) the count for a particular item using
And simply accessing the count for an item is done using
 indexing notation.
I’ve just finished reading through the second early access version of Julia in Action by Chris von Csefalvay. In the chapter on Strings the author present a nice example in which he counts the times each character speaks in Shakespeare’s Hamlet. I couldn’t help but think that this would’ve been even more elegant using an
Tomorrow we’ll take a look at an extremely useful data structure: a graph. Until then, feel free to check out the full code for today on github.