Erlang Thursday – queue:head/1

Today’s Erlang Thursday continues to dig into the Okasaki API of Erlang’s queue module, and take a look at queue:head/1.

queue:head/1 takes a queue as it’s first argument, and returns the first item in the queue.

Queue = queue:from_list([1, 2, 3, 4, 5]).
% {[5,4],[1,2,3]}
queue:head(Queue).
% 1
Queue.
% {[5,4],[1,2,3]}

As we can see in the example above, queue:head/1 function does not modify the original queue at all, but just returns the first item.

Because queue:head/1 only returns the value found at the head of the queue, and not a tagged tuple, it raises an error if we try to get the head item from an empty queue.

EmptyQueue = queue:new().
% {[],[]}
queue:head(EmptyQueue).
%** exception error: empty
%     in function  queue:head/1
%        called as queue:head({[],[]})

To be safe, and not get the error raised on an empty queue, the queue module also defines a function queue:is_empty/1 that you can use to check if a queue is empty.

queue:is_empty(EmptyQueue).
% true

Like queue:cons/2, and other functions of the Okasaki API, there is also a function queue:daeh (head backwards), to get the last item from the queue, as well as an alias for queue:daeh/1 of queue:last/1.

queue:daeh(Queue).
% 5
queue:last(Queue).
% 5

Both queue:daeh/1 and queue:last/1 also raise an error of empty if you call them with an empty queue as the argument.

queue:daeh(EmptyQueue).
% ** exception error: empty
%      in function  queue:get_r/1
%         called as queue:get_r({[],[]})
queue:last(EmptyQueue).
% ** exception error: empty
%      in function  queue:get_r/1
%         called as queue:get_r({[],[]})

And if we look at the error that is raised on queue:daeh/1 and queue:last/1, we see that the error is coming from queue:get_r/1 from the Extended API. If we look at the behavior of queue:get_r/1 it looks like queue:tail/1 and queue:daeh/1 are indeed just aliases for queue:get_r/1.

queue:get_r(Queue).
% 5
queue:get_r(EmptyQueue).
% ** exception error: empty
%      in function  queue:get_r/1
%         called as queue:get_r({[],[]})
queue:get_r(Queue).
% 5
Queue.
% {[5,4],[1,2,3]}

–Proctor

1 thought on “Erlang Thursday – queue:head/1

  1. Pingback: Erlang Thursday – queue:peek/1Proctor It | Proctor It

Comments are closed.