Created
March 28, 2018 14:33
-
-
Save kreas/02302e5c63089f793d6b9d0c25aa16e0 to your computer and use it in GitHub Desktop.
Example of using erlang queues for efficient FIFO (first in first out) processing.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Create a new queue | |
iex> q = :queue.new() | |
# Add 1 to the queue. Remember Elixir is immutable so :queue.in(1, q) returns a new queue | |
iex> q = :queue.in(1, q) | |
...> {[1], []} | |
# Add a few more | |
iex> q = :queue.in(2, q) | |
...> {[2], [1]} | |
iex> q = :queue.in(3, q) | |
...> {[3, 2], [1]} | |
iex> q = :queue.in(4, q) | |
...> {[4, 3, 2], [1]} | |
iex> q = :queue.in(5, q) | |
...> {[5, 4, 3, 2], [1]} | |
# Notice that although we haven't processed 1 it is automatically moved from | |
# to the right list. This is the next item to be proccessed in our queue. | |
# Lets grab some items from the queue. | |
iex> {{value: n}, q} = :queue.out(q) | |
...> {{:value, 1}, {[5, 4, 3], [2]}} | |
# Using pattern matching we've assigned first element from the queue to n | |
# now if you look at your queue you'll see that 2 is the next element. We've | |
# also reassigned q to the new queue returned by the function. | |
iex> q | |
...> {[5, 4, 3], [2]} | |
# Let's process the rest of the queue | |
iex> {{value: n}, q} = :queue.out(q) | |
...> {{:value, 1}, {[5, 4], [3]}} | |
iex> {{value: n}, q} = :queue.out(q) | |
...> {{:value, 1}, {[5], [4]}} | |
iex> {{value: n}, q} = :queue.out(q) | |
...> {{:value, 1}, {[], [5]}} | |
iex> {{value: n}, q} = :queue.out(q) | |
...> {{:value, 1}, {[], []}} | |
iex> {{value: n}, q} = :queue.out(q) | |
...> ** (MatchError) no match of right hand side value: {:empty, {[], []}} | |
# We've just emptied the queue. If you execute :queue.out(q) on an empty queue | |
# you'll get an error. That's OK, this can easily be handled. | |
# Happy queueing. :) | |
# http://erlang.org/doc/man/queue.html |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment