Data Structures
Let's have a go at building some useful data structures, namely Stack, Queue and PriorityQueue:
Before we begin, recall that defining a function with type
instead of var
and const
simply ensures that the typename
of the returned object is the same as that of the function. (Calling info()
on the object will expose its typename, so we can do some basic runtime type checking if we need to)
It's good practice to define all constructor functions (functions that define and return an object) with the keyword type
.
Stack
We'll begin with the most basic structure, the Stack.
Now that we've defined our Stack constructor, we can go ahead and use it to generate a new Struct object.
Great, we were able to successfully push and pop off our new stack.
Note that we also provided a parameter (max) to our constructor, and defaulted it to None
.
Since we constructed the stack without providing a value to max
, our stack can get infinitely large (within the limits of of the physical realm, of course). Let's try creating a stack with a specified max size.
We've successfully capped our stack!
Queue
Let's move on to a slightly different data structure: Queue
Queues are different to Stacks in that they are First In, First Out rather than First In, Last Out.
The only real difference is that instead of pushing and popping, we are enqueuing and dequeuing.
As with the Stack, we can also set a max size by passing in a number to the max
parameter on construction.
Priority Queue
Now for something a little more complicated, a Priority Queue.
A priority queue maintains a sorted list from high priority to low priority.
This time, every time we enqueue a value, we need to pass alongside it a priority value. The queue then sorts the value into its correct spot.
Bear in mind, this is a naive implementation of a priority queue, and there exist more complex and efficient algorithms than simply sorting on enqueue.
Notice we also provide a get
function that returns our values without their priorities. We needed to import functional
to make use of map
here.
Let's walk through the flow.
We add "A" with a priority of 1 -> ["A"]
We add "B" with a priority of 2 -> ["A", "B"]
We add "C" with a priority of 1 -> ["A", "C", "B"]
We add "D" with a priority of 0 -> ["D", "A", "C", "B"]
And just like that, we've built out three useful structures that you can re-use in your own codebase!
Copy the code and modify it to experiment with how things work.
If you wanted to type check a value before adding it to the Stack or Queue, how would you do it? (Hint: check out the list of built-in functions for the answer)
Last updated