|
| 1 | +# About |
| 2 | + |
| 3 | +The Gleam standard library implements a `Queue` type in the `gleam/queue` module. It is similar to the `List` type, but with a few key differences: |
| 4 | + |
| 5 | +- The `Queue` type doesn't have a literal syntax that can be used to construct queues or pattern match on them. |
| 6 | +- Elements can be efficiently added to and removed from both the front and back of the `Queue` type, while the `List` type can only efficiently add and remove elements from the front. |
| 7 | + |
| 8 | +Most of the time you will want to use the `List` type, but when you need to be able to add and remove from the end of a collection, the `Queue` type is a good choice. |
| 9 | + |
| 10 | +Queues can be created using the `queue.new` and `queue.from_list` functions: |
| 11 | + |
| 12 | +```gleam |
| 13 | +let empty = queue.new() |
| 14 | +let one_to_four = queue.from_list([1, 2, 3, 4]) |
| 15 | +``` |
| 16 | + |
| 17 | +Elements can be added to the queue using the `queue.push_front` and `queue.push_back` functions: |
| 18 | + |
| 19 | +```gleam |
| 20 | +let one_to_four = queue.from_list([1, 2, 3, 4]) |
| 21 | +let one_to_five = queue.push_back(one_to_four, 5) |
| 22 | +let zero_to_five = queue.push_front(one_to_five, 0) |
| 23 | +``` |
| 24 | + |
| 25 | +Elements can be removed from the queue using the `queue.pop_front` and `queue.pop_back` functions: |
| 26 | + |
| 27 | +```gleam |
| 28 | +let one_to_four = queue.from_list([1, 2, 3, 4]) |
| 29 | +
|
| 30 | +queue.pop_back(one_to_four) |
| 31 | +// -> Ok(#(4, queue.from_list([1, 2, 3]))) |
| 32 | +
|
| 33 | +queue.pop_front(one_to_four) |
| 34 | +// -> Ok(#(1, queue.from_list([2, 3, 4]))) |
| 35 | +
|
| 36 | +queue.pop_front(queue.new()) |
| 37 | +// -> Error(Nil) |
| 38 | +``` |
| 39 | + |
| 40 | +A queue can be converted into a list using the `queue.to_list` function: |
| 41 | + |
| 42 | +```gleam |
| 43 | +let one_to_four = queue.from_list([1, 2, 3, 4]) |
| 44 | +queue.to_list(one_to_four) |
| 45 | +// -> [1, 2, 3, 4] |
| 46 | +``` |
| 47 | + |
| 48 | +## Queue equality |
| 49 | + |
| 50 | +Due to how queues are implemented, two queues with the same elements in the same order may not be equal according to the `==` operator, which compares values structurally. For example: |
| 51 | + |
| 52 | +```gleam |
| 53 | +let empty = queue.new() |
| 54 | +let a = queue.push_front(empty, 1) |
| 55 | +let b = queue.push_back(empty, 1) |
| 56 | +a == b |
| 57 | +// -> False |
| 58 | +``` |
| 59 | + |
| 60 | +If you need to compare two queues for equality use can use the `queue.is_logically_equal` function. |
| 61 | + |
| 62 | +```gleam |
| 63 | +queue.is_logically_equal(a, b, fn(x, y) { x == y }))) |
| 64 | +// -> True |
| 65 | +``` |
0 commit comments