Making a heterogeneous stack in Julia

So, data structures in Julia can be a little tricky. The Collections module provides for a Priority Queue and some Heap functions. Arrays are nice, but sometimes a more complex structure is needed, say a heterogeneous stack. Firstly, a composite type can be created, and this is essentially a form of record, equivalent to a  struct in C. Consider the following example:

type Point

In Julia this is known as a “user-defined concrete type”, and contains two field names x and y, annotated with types (Int in this case). Then a variable of this type can be created in the following manner:

p = Point(7,12)

Therefore p.x has the value 7 and p.y has the value 12. The type here is applied like a function, and is termed a constructor. Now how to turn this into a stack? First create an empty array from the type Point.

stackP = Point[]

Then simply add to the stack using push!, and extract from the stack using pop!.

x = pop!(stackP)

It works nicely, the only issue was finding some sample code that actually explained how this would work – again the official documentation is not the best at explaining things like this, and is certainly lacking in examples.

If you want a more comprehensive set of data structures nicely packaged up, check out this DataStructures on Github.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s