Motoko FIFO Queue

If anyone needs one, feel free to use it…

5 Likes

It might be worth having something like this in the standard library? (nudge nudge ; )

3 Likes

How to get the size of the queue ? How to setup the capacity for the queue

The Queue is actually a tuple containing two functional Lists: (List, List), so you can check the sizes for both of these lists and add them together:

import List "mo:base/List";
import Debug "mo:base/Debug";

import Queue "Queue";

var a: Queue.Queue<Nat> = Queue.nil();
a := Queue.enqueue(1, a);
a := Queue.enqueue(2, a);
a := Queue.enqueue(3, a);

// sum the size of both lists
let s = List.size(a.0) + List.size(a.1);

Debug.print(debug_show(s));

And they’ll grow as you enqueue values, you don’t need to set a capacity.

I’ve added a size() method to the repo for you, you can call that if you prefer:

let s = Queue.size(a);

The standard library can’t contain everything. But if you add it to the vessel package set (Motoko Packages with instructions at vessel-package-set/CONTRIBUTING.md at main · dfinity/vessel-package-set · GitHub) everyone can easily use it.

Oh could do yes, thanks. Deque probably covers this now, that post was a long while ago (when the std lib was just a toddler!)