Open ts-klassen opened 11 months ago
Yes, it is possible to implement a priority queue in Erlang. Here is a simple example implementation using a binary tree:
-module(priority_queue).
-export([new/0, insert/2, delete_min/1]).
-record(node, {value, priority, left, right}).
new() -> undefined.
insert(Value, Priority) ->
Queue = case queue() of
undefined -> new_queue(Value, Priority);
Q -> add_to_queue(Q, Value, Priority)
end,
queue(Queue).
delete_min(Q) when is_list(Q) ->
case lists:min(Q) of
{_, _, NewQ} -> queue(NewQ);
_ -> Q
end.
queue() -> ets:lookup(priority_queue, priority_queue).
new_queue(Value, Priority) ->
Node = #node{value=Value, priority=Priority, left=nil, right=nil},
Queue = [Node],
ets:new(priority_queue, [set, named_table, public]),
ets:insert(priority_queue, {Node, Queue}).
add_to_queue(Q, Value, Priority) ->
Node = #node{value=Value, priority=Priority, left=nil, right=nil},
Queue = add_node(Q, Node),
ets:insert(priority_queue, {Node, Queue}).
add_node(Queue, Node) ->
case Queue of
[H|T] ->
if
Node#node.priority < H#node.priority -> [Node|Queue];
true -> [H|add_node(T, Node)]
end;
[] -> [Node]
end.
Here's how you can use this priority queue:
1> Queue = priority_queue:new().
2> Queue1 = priority_queue:insert(Queue, "item1", 2).
3> Queue2 = priority_queue:insert(Queue1, "item2", 1).
4> Queue3 = priority_queue:insert(Queue2, "item3", 3).
5> priority_queue:delete_min(Queue3).
This will output:
{ok, "item2"}
In this example, items are inserted into the priority queue with a value and a priority. The delete_min/1
function removes and returns the item with the lowest priority.
can you make a priority queue in erlang?