### Dictionary Example Source: https://github.com/randy3k/collections/blob/master/docs/index.html Demonstrates dictionary creation and usage, including setting and getting values with various key types. Compares to R environments, noting that dict() does not leak memory and supports various key types. The library should be loaded with warn.conflicts = FALSE. ```r library(collections, warn.conflicts = FALSE) d <- dict() e <- new.env() d$set(e, 1)$set(sum, 2)$set(c(1L, 2L), 3) d$get(c(1L, 2L)) ``` -------------------------------- ### Queue Example Source: https://github.com/randy3k/collections/blob/master/docs/index.html Demonstrates basic queue operations: initialization, pushing elements, and popping elements. The library should be loaded with warn.conflicts = FALSE. ```r library(collections, warn.conflicts = FALSE) q <- queue() q$push(1)$push(2) q$pop() ``` -------------------------------- ### Stack Example Source: https://github.com/randy3k/collections/blob/master/docs/index.html Demonstrates basic stack operations: initialization, pushing elements, and popping elements. The library should be loaded with warn.conflicts = FALSE. ```r library(collections, warn.conflicts = FALSE) s <- stack() s$push(1)$push(2) s$pop() ``` -------------------------------- ### Create a Stack with Initial Items in R Source: https://github.com/randy3k/collections/blob/master/docs/reference/stack.html Shows how to initialize a stack with a list of items and then add more items. Useful when you need to start with pre-existing data in the stack. ```r s <- stack(list("foo", "bar")) s$push("baz")$push("bla") ``` -------------------------------- ### Ordered Dictionary Example Source: https://github.com/randy3k/collections/blob/master/docs/index.html Demonstrates ordered dictionary creation, setting key-value pairs, and converting to a list while preserving order. The library should be loaded with warn.conflicts = FALSE. ```r library(collections, warn.conflicts = FALSE) d <- ordered_dict() d$set("b", 1)$set("a", 2) d$as_list() ``` -------------------------------- ### Create and Use an Unordered Dictionary (Hash Map) Source: https://context7.com/randy3k/collections/llms.txt Demonstrates creating a hash map, setting and getting key-value pairs, handling missing keys with defaults, and removing items. Supports various key types including atomic vectors, environments, and functions. ```r library(collections) # String keys d <- dict() d$set("apple", 5)$set("banana", 3)$set("cherry", 8) d$size() # [1] 3 d$has("banana") # [1] TRUE d$get("apple") # [1] 5 d$get("mango", 0) # [1] 0 — default value when key absent d$pop("banana") # [1] 3 — returns and removes d$size() # [1] 2 # Overwrite an existing key d$set("apple", 99) d$get("apple") # [1] 99 length(d$keys()) # [1] 2 (no duplicate key) # Initialize from a named list d2 <- dict(list(x = 1, y = 2, z = 3)) d2$as_list() # named list (order not guaranteed) # Initialize with explicit keys list (supports non-character keys) e1 <- new.env(); e2 <- new.env() d3 <- dict(list(100, 200), list(e1, e2)) d3$get(e1) # [1] 100 d3$get(e2) # [1] 200 # Vector and object keys d4 <- dict() d4$set(c(1L, 2L, 3L), "integer vector key") d4$set(LETTERS, "character vector key") f <- function(x) x^2 d4$set(f, "function key") d4$get(c(1L, 2L, 3L)) # [1] "integer vector key" d4$get(f) # [1] "function key" # Merge two dicts d5 <- dict(list(a = 1, b = 2)) d6 <- dict(list(b = 99, c = 3)) d5$update(d6) # keys from d6 overwrite d5 where they overlap d5$get("b") # [1] 99 d5$get("c") # [1] 3 # cls() for class inspection cls(d5) # [1] "dict" ``` -------------------------------- ### Priority Queue Example Source: https://github.com/randy3k/collections/blob/master/docs/index.html Demonstrates priority queue operations: initialization, pushing elements with default and custom priorities, and popping elements in order of priority. The library should be loaded with warn.conflicts = FALSE. ```r library(collections, warn.conflicts = FALSE) pq <- priority_queue() pq$push("not_urgent") pq$push("urgent", priority = 2) pq$push("not_as_urgent", priority = 1) pq$pop() pq$pop() pq$pop() ``` -------------------------------- ### Deque Example Source: https://github.com/randy3k/collections/blob/master/docs/index.html Demonstrates basic deque operations: initialization, pushing elements to the right, pushing elements to the left, and popping elements from the left. The library should be loaded with warn.conflicts = FALSE. ```r library(collections, warn.conflicts = FALSE) dq <- deque() dq$push(1)$pushleft(2) dq$pop() ``` -------------------------------- ### Install collections Package Source: https://github.com/randy3k/collections/blob/master/docs/index.html Install the released version from CRAN or the latest development version from GitHub using devtools. ```r install.packages("collections") ``` ```r devtools::install_github("randy3k/collections") ``` -------------------------------- ### Install collections Package Development Version Source: https://github.com/randy3k/collections/blob/master/README.md Install the latest development version of the collections package directly from GitHub. ```r devtools::install_github("randy3k/collections") ``` -------------------------------- ### Install collections Package from CRAN Source: https://github.com/randy3k/collections/blob/master/README.md Use this command to install the latest stable version of the collections package from CRAN. ```r install.packages("collections") ``` -------------------------------- ### Queue Methods Source: https://github.com/randy3k/collections/blob/master/docs/reference/queue.html Provides methods to interact with the queue, including adding items, removing items, peeking at the next item, clearing the queue, getting its size, converting it to a list, and printing its contents. ```APIDOC ## Queue Methods ### Description These methods are exposed by the queue object for managing its contents. ### Methods - **.$push(item)** - Adds an item to the end of the queue. - **item**: any R object. - **.$pop()** - Removes and returns the item from the front of the queue. - **.$peek()** - Returns the item at the front of the queue without removing it. - **.$clear()** - Removes all items from the queue. - **.$size()** - Returns the number of items currently in the queue. - **.$as_list()** - Converts the queue to an R list. - **.$print()** - Prints the contents of the queue. ``` -------------------------------- ### dict Source: https://context7.com/randy3k/collections/llms.txt Creates an unordered dictionary (hash map) using the TommyDS hash table. Keys can be scalar strings, atomic vectors, environments, or functions. Supports methods for setting, getting, removing, popping, checking existence, retrieving keys/values, updating, clearing, and converting to a list. ```APIDOC ## `dict(items = NULL, keys = NULL)` — Unordered Dictionary (Hash Map) Creates a hash map powered by the TommyDS hash table. Keys can be scalar strings, atomic vectors, environments, or functions. Iteration order is not guaranteed. Methods: `$set(key, value)`, `$get(key, default)`, `$remove(key, silent = FALSE)`, `$pop(key, default)`, `$has(key)`, `$keys()`, `$values()`, `$update(d)`, `$clear()`, `$size()`, `$as_list()`, `$print()`. ``` -------------------------------- ### Initialize Queue with Items and Add More Source: https://github.com/randy3k/collections/blob/master/docs/reference/queue.html Shows how to initialize a queue with a list of items and then add more items using chained push operations. ```R q <- queue(list("foo", "bar")) q$push("baz")$push("bla") ``` -------------------------------- ### Create and Use a Queue Source: https://github.com/randy3k/collections/blob/master/docs/reference/queue.html Demonstrates creating an empty queue, adding items, and removing them. The output of pop operations is shown. ```R q <- queue() q$push("first") q$push("second") q$pop() # first #> [1] "first" q$pop() # second #> [1] "second" ``` -------------------------------- ### Initialize Priority Queue with Items Source: https://github.com/randy3k/collections/blob/master/docs/reference/priority_queue.html Shows how to initialize a priority queue with a list of items and their corresponding priorities. Further items can be added using the push method, which can be chained. ```R q <- priority_queue(list("not_urgent", "urgent"), c(0, 2)) q$push("not_as_urgent", 1)$push("not_urgent2") ``` -------------------------------- ### Get class of a dictionary object Source: https://github.com/randy3k/collections/blob/master/docs/reference/cls.html Use `cls` to determine the class of a dictionary object. This function is a specialized version of `class` for collection objects. ```r d <- dict() cls(d) #> [1] "dict" ``` -------------------------------- ### Initialize Priority Queue with Items Source: https://github.com/randy3k/collections/blob/master/docs/reference/PriorityQueue.html Shows how to initialize a priority queue with a list of items and their corresponding priorities. Subsequent pushes can add more items, including those with default priorities. ```R q <- PriorityQueue(list("not_urgent", "urgent"), c(0, 2)) q$push("not_as_urgent", 1)$push("not_urgent2") ``` -------------------------------- ### Initialize Queue from List Source: https://context7.com/randy3k/collections/llms.txt Shows how to create a queue pre-populated with items from an existing R list. The insertion order is preserved. ```r # Initialize from an existing list q2 <- queue(list(10L, 20L, 30L)) q2$as_list() # list(10L, 20L, 30L) — preserves insertion order ``` -------------------------------- ### Create and Modify Dictionary Source: https://github.com/randy3k/collections/blob/master/docs/reference/dict.html Demonstrates creating a dictionary with initial items, setting new key-value pairs, and retrieving values. Chaining of set methods is also shown. ```R d <- dict(list(apple = 5, orange = 10)) d$set("banana", 3) d$get("apple") ``` ```R d$set("orange", 3)$set("pear", 7) # chain methods ``` -------------------------------- ### Create and Use an Insertion-Order Dictionary Source: https://context7.com/randy3k/collections/llms.txt Demonstrates creating a dictionary that preserves insertion order. Shows how keys maintain their order, values are updated, and items can be popped from either end. Supports environment and function keys. ```r library(collections) # Insertion order is preserved od <- ordered_dict() od$set("c", 3)$set("a", 1)$set("b", 2) od$keys() # list("c", "a", "b") — insertion order od$values() # list(3, 1, 2) od$as_list() # $c [1] 3 $a [1] 1 $b [1] 2 # Re-setting an existing key updates value but keeps original position od$set("c", 99) od$keys() # list("c", "a", "b") — "c" stays first od$get("c") # [1] 99 # popitem: remove last inserted item od2 <- ordered_dict(list(x = 10, y = 20, z = 30)) od2$popitem(last = TRUE) # list(key = "z", value = 30) od2$popitem(last = FALSE) # list(key = "x", value = 10) od2$keys() # list("y") # Initialize with parallel items + keys lists keys_list <- list("first", "second", "third") items_list <- list(list(id=1), list(id=2), list(id=3)) od3 <- ordered_dict(items_list, keys_list) od3$keys() # list("first", "second", "third") # Object keys (environment, function) od4 <- ordered_dict() f1 <- function() "f1" f2 <- function() "f2" od4$set(f1, "result_f1")$set(f2, "result_f2") od4$get(f1) # [1] "result_f1" od4$keys() # list(f1, f2) # Default value on missing key od4$get("missing_key", "fallback") # [1] "fallback" # Serialize / unserialize od5 <- ordered_dict(list(a = 1, b = 2)) od5_restored <- unserialize(serialize(od5, NULL)) od5_restored$keys() # list("a", "b") ``` -------------------------------- ### Create and Use a Priority Queue Source: https://github.com/randy3k/collections/blob/master/docs/reference/PriorityQueue.html Demonstrates creating an empty priority queue, pushing items with and without explicit priorities, and then popping them in order of priority. Items with higher numerical priority values are popped first. ```R q <- PriorityQueue() q$push("not_urgent") q$push("urgent", priority = 2) q$push("not_as_urgent", priority = 1) q$pop() # urgent #> [1] "urgent" q$pop() # not_as_urgent #> [1] "not_as_urgent" q$pop() # not_urgent #> [1] "not_urgent" ``` -------------------------------- ### Initialize Deque with Items and Add More Source: https://github.com/randy3k/collections/blob/master/docs/reference/deque.html Shows how to initialize a deque with a list of items and then add more elements to both the left and right ends. ```R q <- deque(list("foo", "bar")) q$push("baz")$pushleft("bla") ``` -------------------------------- ### Dictionary Operations with Various Key Types Source: https://github.com/randy3k/collections/blob/master/README.md Illustrates creating a dictionary and setting key-value pairs using different types of keys, including R environments, functions, and vectors. It also shows how to retrieve a value using its key. ```r d <- dict() e <- new.env() d$set(e, 1)$set(sum, 2)$set(c(1L, 2L), 3) d$get(c(1L, 2L)) ``` -------------------------------- ### Create and Use a Priority Queue Source: https://github.com/randy3k/collections/blob/master/docs/reference/priority_queue.html Demonstrates creating an empty priority queue, pushing items with and without explicit priorities, and popping items in order of priority. Items with higher numerical priority values are popped first. ```R q <- priority_queue() q$push("not_urgent") q$push("urgent", priority = 2) q$push("not_as_urgent", priority = 1) q$pop() # urgent #> [1] "urgent" q$pop() # not_as_urgent #> [1] "not_as_urgent" q$pop() # not_urgent #> [1] "not_urgent" ``` -------------------------------- ### Basic LIFO Stack Usage Source: https://context7.com/randy3k/collections/llms.txt Demonstrates the fundamental push, pop, and peek operations for a LIFO stack. Items are added and removed from the top. ```r library(collections) # Basic LIFO usage s <- stack() s$push("first")$push("second")$push("third") s$size() # [1] 3 s$peek() # [1] "third" — top of stack s$pop() # [1] "third" s$pop() # [1] "second" s$size() # [1] 1 ``` -------------------------------- ### Create and Use a Max-Heap Priority Queue Source: https://context7.com/randy3k/collections/llms.txt Demonstrates creating a priority queue, pushing items with priorities, and popping them in order of priority. Higher numeric values indicate higher priority. Initialization with parallel vectors is also shown. ```r library(collections) # Basic priority ordering (higher number = higher priority) pq <- priority_queue() pq$push("low", priority = 1) pq$push("critical", priority = 10) pq$push("medium", priority = 5) pq$push("urgent", priority = 8) pq$size() # [1] 4 pq$pop() # [1] "critical" (priority 10) pq$pop() # [1] "urgent" (priority 8) pq$pop() # [1] "medium" (priority 5) pq$pop() # [1] "low" (priority 1) # Initialize with parallel items + priorities vectors jobs <- list("job_A", "job_B", "job_C") prios <- c(3, 1, 2) pq2 <- priority_queue(jobs, prios) pq2$pop() # [1] "job_A" (priority 3) # as_list() returns items sorted by descending priority (non-destructive) pq3 <- priority_queue() pq3$push("c", 1)$push("a", 3)$push("b", 2) pq3$as_list() # list("a", "b", "c") # Default priority = 0 (FIFO among equal-priority items is not guaranteed) pq4 <- priority_queue() pq4$push("x")$push("y")$push("z") # all priority 0 pq4$size() # [1] 3 # Error on empty queue tryCatch(priority_queue()$pop(), error = function(e) message(e$message)) # priority_queue is empty ``` -------------------------------- ### Initialize Stack from List Source: https://context7.com/randy3k/collections/llms.txt Shows how to initialize a stack with elements from a list, where the last element of the list becomes the top of the stack. ```r # Initialize from list — last element becomes the top s2 <- stack(list("a", "b", "c")) s2$peek() # [1] "c" ``` -------------------------------- ### Basic FIFO Queue Usage Source: https://context7.com/randy3k/collections/llms.txt Demonstrates the basic push, pop, and peek operations for a FIFO queue. Chained method calls are supported for mutations. ```r library(collections) # Basic FIFO usage q <- queue() q$push("task_a")$push("task_b")$push("task_c") # chained pushes q$size() # [1] 3 q$peek() # [1] "task_a" — inspect without removing q$pop() # [1] "task_a" q$pop() # [1] "task_b" q$size() # [1] 1 ``` -------------------------------- ### Dictionary with Environment and Function Keys Source: https://github.com/randy3k/collections/blob/master/docs/reference/dict.html Demonstrates using R environments and functions as keys in a dictionary, and retrieving their associated values. ```R # object indexing e <- new.env() d$set(sum, 1)$set(e, 2) d$get(sum) # 1 d$get(e) # 2 ``` -------------------------------- ### queue() — First-In-First-Out Queue Source: https://context7.com/randy3k/collections/llms.txt Creates a FIFO queue backed by a C pairlist. Items are pushed to the back and popped from the front. The constructor accepts an optional list of initial items. Methods include $push(), $pop(), $peek(), $clear(), $size(), $as_list(), and $print(). ```APIDOC ## queue(items = NULL) — First-In-First-Out Queue ### Description Creates a FIFO queue backed by a C pairlist. Items are pushed to the back and popped from the front. The constructor accepts an optional `list` of initial items. ### Methods - `$push(item)`: Adds an item to the back of the queue. - `$pop()`: Removes and returns the item from the front of the queue. - `$peek()`: Returns the item at the front of the queue without removing it. - `$clear()`: Removes all items from the queue. - `$size()`: Returns the number of items in the queue. - `$as_list()`: Converts the queue to an R list, preserving insertion order. - `$print()`: Prints the queue contents. ### Example ```r library(collections) # Basic FIFO usage q <- queue() q$push("task_a")$push("task_b")$push("task_c") # chained pushes q$size() # [1] 3 q$peek() # [1] "task_a" — inspect without removing q$pop() # [1] "task_a" q$pop() # [1] "task_b" q$size() # [1] 1 # Initialize from an existing list q2 <- queue(list(10L, 20L, 30L)) q2$as_list() # list(10L, 20L, 30L) — preserves insertion order # NULL values are supported q3 <- queue() q3$push(NULL)$push(NULL) q3$pop() # NULL q3$size() # [1] 1 (second NULL still in queue) # Serialize/unserialize (e.g., for caching or parallel workers) q4 <- queue(list(1, 2, 3)) q4_saved <- serialize(q4, NULL) q4_restored <- unserialize(q4_saved) q4_restored$size() # [1] 3 q4_restored$pop() # [1] 1 # Error on empty queue tryCatch(queue()$pop(), error = function(e) message(e$message)) # queue is empty ``` ``` -------------------------------- ### Queue Operations Source: https://github.com/randy3k/collections/blob/master/README.md Demonstrates basic queue operations: creating a queue, pushing elements, and popping an element. The `push` method returns the queue itself, allowing for method chaining. ```r q <- queue() q$push(1)$push(2) q$pop() ``` -------------------------------- ### Ordered Dictionary Operations Source: https://github.com/randy3k/collections/blob/master/README.md Demonstrates creating an ordered dictionary, setting key-value pairs, and converting the dictionary to a list while preserving the insertion order. ```r d <- ordered_dict() d$set("b", 1)$set("a", 2) d$as_list() ``` -------------------------------- ### Create and Manipulate an Ordered Dictionary Source: https://github.com/randy3k/collections/blob/master/docs/reference/ordered_dict.html Demonstrates the creation of an ordered dictionary, adding elements, retrieving values, and removing elements while preserving order. Chaining method calls is also shown. ```R d <- ordered_dict(list(apple = 5, orange = 10)) d$set("banana", 3) d$get("apple") #> [1] 5 d$as_list() # the order the item is preserved #> $apple #> [1] 5 #> #> $orange #> [1] 10 #> #> $banana #> [1] 3 #> d$pop("orange") #> [1] 10 d$as_list() # "orange" is removed #> $apple #> [1] 5 #> #> $banana #> [1] 3 #> d$set("orange", 3)$set("pear", 7) # chain methods ``` -------------------------------- ### Create and Manipulate a Stack in R Source: https://github.com/randy3k/collections/blob/master/docs/reference/stack.html Demonstrates creating an empty stack, pushing items, and popping them. Use this to manage data where the last added item should be the first one removed. ```r s <- stack() s$push("first") s$push("second") s$pop() # second s$pop() # first ``` -------------------------------- ### Create and manipulate an Ordereddict Source: https://github.com/randy3k/collections/blob/master/docs/reference/OrderedDict.html Demonstrates the creation of an Ordereddict, adding items, retrieving values, and removing items. The order of elements is preserved. ```R d <- Ordereddict(list(apple = 5, orange = 10)) d$set("banana", 3) d$get("apple") #> [1] 5 d$as_list() # the order the item is preserved #> $apple #> [1] 5 #> #> $orange #> [1] 10 #> #> $banana #> [1] 3 #> d$pop("orange") #> [1] 10 d$as_list() # "orange" is removed #> $apple #> [1] 5 #> #> $banana #> [1] 3 #> d$set("orange", 3)$set("pear", 7) # chain methods ``` -------------------------------- ### Stack Operations Source: https://github.com/randy3k/collections/blob/master/README.md Illustrates basic stack operations: creating a stack, pushing elements, and popping an element. Similar to queues, the `push` method supports chaining. ```r s <- stack() s$push(1)$push(2) s$pop() ``` -------------------------------- ### Stack for Function Call Simulation Source: https://context7.com/randy3k/collections/llms.txt Illustrates using a stack to simulate a function call stack, managing frames with function names and depths. ```r # Use as a function-call stack simulation call_stack <- stack() call_stack$push(list(fn = "main", depth = 0)) call_stack$push(list(fn = "helper", depth = 1)) call_stack$push(list(fn = "inner", depth = 2)) while (call_stack$size() > 0) { frame <- call_stack$pop() cat("returning from:", frame$fn, "at depth", frame$depth, "\n") } # returning from: inner at depth 2 # returning from: helper at depth 1 # returning from: main at depth 0 ``` -------------------------------- ### Dictionary with Vector and Letter Keys Source: https://github.com/randy3k/collections/blob/master/docs/reference/dict.html Shows how to use atomic vectors and character vectors (like LETTERS) as keys in a dictionary, and how to retrieve values associated with these keys. ```R # vector indexing d$set(c(1L, 2L), 3)$set(LETTERS, 26) d$get(c(1L, 2L)) # 3 d$get(LETTERS) # 26 ``` -------------------------------- ### stack() — Last-In-First-Out Stack Source: https://context7.com/randy3k/collections/llms.txt Creates a LIFO stack backed by a C pairlist. Items are pushed and popped from the same end (top). The constructor accepts an optional list of initial items. Methods include $push(), $pop(), $peek(), $clear(), $size(), $as_list(), and $print(). ```APIDOC ## stack(items = NULL) — Last-In-First-Out Stack ### Description Creates a LIFO stack backed by a C pairlist. Items are pushed and popped from the same end (top). The constructor accepts an optional `list` of initial items. ### Methods - `$push(item)`: Adds an item to the top of the stack. - `$pop()`: Removes and returns the item from the top of the stack. - `$peek()`: Returns the item at the top of the stack without removing it. - `$clear()`: Removes all items from the stack. - `$size()`: Returns the number of items in the stack. - `$as_list()`: Converts the stack to an R list, with the top of the stack as the last element. - `$print()`: Prints the stack contents. ### Example ```r library(collections) # Basic LIFO usage s <- stack() s$push("first")$push("second")$push("third") s$size() # [1] 3 s$peek() # [1] "third" — top of stack s$pop() # [1] "third" s$pop() # [1] "second" s$size() # [1] 1 # Initialize from list — last element becomes the top s2 <- stack(list("a", "b", "c")) s2$peek() # [1] "c" # Use as a function-call stack simulation call_stack <- stack() call_stack$push(list(fn = "main", depth = 0)) call_stack$push(list(fn = "helper", depth = 1)) call_stack$push(list(fn = "inner", depth = 2)) while (call_stack$size() > 0) { frame <- call_stack$pop() cat("returning from:", frame$fn, "at depth", frame$depth, "\n") } # returning from: inner at depth 2 # returning from: helper at depth 1 # returning from: main at depth 0 # Clear and reuse s3 <- stack(list(1, 2, 3)) s3$clear() s3$size() # [1] 0 ``` ``` -------------------------------- ### Serialize and Unserialize Queue Source: https://context7.com/randy3k/collections/llms.txt Demonstrates how to serialize a queue to a raw vector and then unserialize it back, useful for caching or inter-process communication. ```r # Serialize/unserialize (e.g., for caching or parallel workers) q4 <- queue(list(1, 2, 3)) q4_saved <- serialize(q4, NULL) q4_restored <- unserialize(q4_saved) q4_restored$size() # [1] 3 q4_restored$pop() # [1] 1 ``` -------------------------------- ### deque() — Double-Ended Queue Source: https://context7.com/randy3k/collections/llms.txt Creates a deque supporting O(1) push/pop at both ends. Methods include $push(), $pushleft(), $pop(), $popleft(), $peek(), $peekleft(), $extend(), $extendleft(), $remove(), $clear(), $size(), $as_list(), and $print(). ```APIDOC ## deque(items = NULL) — Double-Ended Queue ### Description Creates a deque supporting O(1) push/pop at both ends. The constructor accepts an optional list of initial items. ### Methods - `$push(item)`: Adds an item to the right end of the deque. - `$pushleft(item)`: Adds an item to the left end of the deque. - `$pop()`: Removes and returns the item from the right end of the deque. - `$popleft()`: Removes and returns the item from the left end of the deque. - `$peek()`: Returns the item at the right end of the deque without removing it. - `$peekleft()`: Returns the item at the left end of the deque without removing it. - `$extend(deque)`: Appends all items from another deque to the right end. - `$extendleft(deque)`: Prepends all items from another deque to the left end (items are added in reverse order). - `$remove(item)`: Removes the first occurrence of a specific item from the deque. - `$clear()`: Removes all items from the deque. - `$size()`: Returns the number of items in the deque. - `$as_list()`: Converts the deque to an R list. - `$print()`: Prints the deque contents. ### Example ```r library(collections) # Push and pop from both ends dq <- deque() dq$push("right1")$push("right2") # add to right dq$pushleft("left1")$pushleft("left2") # add to left dq$size() # [1] 4 dq$peek() # [1] "right2" — rightmost dq$peekleft() # [1] "left2" — leftmost dq$pop() # [1] "right2" dq$popleft() # [1] "left2" # Remove a specific item (first occurrence) dq2 <- deque(list("a", "b", "a", "c")) dq2$remove("a") # removes first "a" dq2$size() # [1] 3 dq2$as_list() # list("b", "a", "c") # Merge two deques with extend / extendleft base_dq <- deque(list(1, 2, 3)) extra_dq <- deque(list(4, 5)) base_dq$extend(extra_dq) # appends 4,5 to the right base_dq$as_list() # list(1, 2, 3, 4, 5) base_dq$extendleft(extra_dq) # prepends extra items (reversed) to the left # extendleft pushes each item one at a time to the left, reversing order # Use as a sliding window buffer window <- deque() stream <- c(10, 20, 30, 40, 50) window_size <- 3L for (val in stream) { window$push(val) if (window$size() > window_size) window$popleft() } window$as_list() # list(30, 40, 50) ``` ``` -------------------------------- ### Deque Push and Pop from Both Ends Source: https://context7.com/randy3k/collections/llms.txt Shows how to add (push, pushleft) and remove (pop, popleft) elements from both the left and right ends of a deque efficiently. ```r library(collections) # Push and pop from both ends dq <- deque() dq$push("right1")$push("right2") # add to right dq$pushleft("left1")$pushleft("left2") # add to left dq$size() # [1] 4 dq$peek() # [1] "right2" — rightmost dq$peekleft() # [1] "left2" — leftmost dq$pop() # [1] "right2" dq$popleft() # [1] "left2" ``` -------------------------------- ### Deque Extend and ExtendLeft Source: https://context7.com/randy3k/collections/llms.txt Illustrates merging one deque into another using `extend` (appends to right) and `extendleft` (prepends to left, reversing order). ```r # Merge two deques with extend / extendleft base_dq <- deque(list(1, 2, 3)) extra_dq <- deque(list(4, 5)) base_dq$extend(extra_dq) # appends 4,5 to the right base_dq$as_list() # list(1, 2, 3, 4, 5) base_dq$extendleft(extra_dq) # prepends extra items (reversed) to the left # extendleft pushes each item one at a time to the left, reversing order ``` -------------------------------- ### Queue Creation Source: https://github.com/randy3k/collections/blob/master/docs/reference/queue.html Creates a new queue object. It can be initialized with a list of items or as an empty queue. ```APIDOC ## queue() ### Description Creates a new queue object. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Arguments - **items** (list, optional) - A list of items to initialize the queue with. Defaults to NULL (an empty queue). ``` -------------------------------- ### Dictionary Operations and Output Source: https://github.com/randy3k/collections/blob/master/docs/reference/dict.html Illustrates converting a dictionary to a list and removing an item using pop. The unordered nature of the dictionary is evident in the output. ```R d$as_list() # unordered d$pop("orange") d$as_list() # "orange" is removed ``` -------------------------------- ### Dictionary Creation Source: https://github.com/randy3k/collections/blob/master/docs/reference/dict.html Creates an ordinary (unordered) dictionary. It can be initialized with a list of items or separate keys and values. ```APIDOC ## dict() ### Description Creates an ordinary (unordered) dictionary (a.k.a. hash). ### Arguments * `items` (list, optional): A list of items to initialize the dictionary with. If NULL, `keys` must be provided. * `keys` (list, optional): A list of keys. If NULL, `names(items)` will be used. ### Example ```R d <- dict(list(apple = 5, orange = 10)) ``` ``` -------------------------------- ### Deque as Sliding Window Buffer Source: https://context7.com/randy3k/collections/llms.txt Shows how a deque can be used to implement a fixed-size sliding window buffer, maintaining the most recent elements. ```r # Use as a sliding window buffer window <- deque() stream <- c(10, 20, 30, 40, 50) window_size <- 3L for (val in stream) { window$push(val) if (window$size() > window_size) window$popleft() } window$as_list() # list(30, 40, 50) ``` -------------------------------- ### Clear and Reuse Stack Source: https://context7.com/randy3k/collections/llms.txt Demonstrates clearing all elements from a stack to reset it for reuse. ```r # Clear and reuse s3 <- stack(list(1, 2, 3)) s3$clear() s3$size() # [1] 0 ``` -------------------------------- ### Priority Queue Operations Source: https://github.com/randy3k/collections/blob/master/README.md Demonstrates the usage of a priority queue. Elements can be pushed with an optional priority level (higher number means higher priority). Elements are popped in order of priority. ```r pq <- priority_queue() pq$push("not_urgent") pq$push("urgent", priority = 2) pq$push("not_as_urgent", priority = 1) pq$pop() pq$pop() pq$pop() ``` -------------------------------- ### PriorityQueue Constructor Source: https://github.com/randy3k/collections/blob/master/docs/reference/PriorityQueue.html Initializes a new PriorityQueue. It can be created empty or with initial items and their priorities. ```APIDOC ## PriorityQueue() ### Description Creates a priority queue (a.k.a heap). ### Parameters #### Arguments * **items** (list) - a list of items * **priorities** (vector) - a vector of integer valued priorities ### Details Initializes a new PriorityQueue with optional items and their corresponding priorities. If priorities are not provided, they default to 0. ``` -------------------------------- ### Priority Queue Methods Source: https://github.com/randy3k/collections/blob/master/docs/reference/priority_queue.html Methods available for interacting with a priority queue object. ```APIDOC ## Priority Queue Methods ### Description These methods allow users to manipulate and query the priority queue. ### Methods - **.$push(item, priority = 0)**: Adds an item to the priority queue. - `item`: any R object. - `priority`: a real number, item with larger priority pops first. - **.$pop()**: Removes and returns the item with the highest priority. - **.$clear()**: Removes all items from the priority queue. - **.$size()**: Returns the number of items in the priority queue. - **.$as_list()**: Returns the items in the priority queue as a list. - **.$print()**: Prints the priority queue. ### Request Example ```R q <- priority_queue() q$push("not_urgent") q$push("urgent", priority = 2) q$push("not_as_urgent", priority = 1) print(q$pop()) # Output: "urgent" print(q$pop()) # Output: "not_as_urgent" print(q$pop()) # Output: "not_urgent" print(q$size()) print(q$as_list()) q$clear() print(q$size()) ``` ``` -------------------------------- ### Stack Creation Source: https://github.com/randy3k/collections/blob/master/docs/reference/stack.html Creates a new stack object. It can be initialized with a list of items or as an empty stack. ```APIDOC ## stack() ### Description Creates a new stack object. ### Parameters #### Path Parameters - **items** (list) - Optional - A list of initial items for the stack. ### Request Example ```R s <- stack() s <- stack(list("foo", "bar")) ``` ``` -------------------------------- ### Dispatching Methods Using `cls()` in Generic Functions Source: https://context7.com/randy3k/collections/llms.txt Demonstrates how `cls()` can be used within a `switch` statement to implement type-specific behavior in generic functions. This allows for tailored processing based on the detected object class. ```r # Useful for dispatch in generic functions process <- function(container) { switch(cls(container), queue = cat("Processing FIFO queue\n"), stack = cat("Processing LIFO stack\n"), priority_queue = cat("Processing heap\n"), dict = cat("Processing hash map\n"), cat("Unknown type\n") ) } process(queue()) # Processing FIFO queue process(priority_queue()) # Processing heap ``` -------------------------------- ### Deque Operations Source: https://github.com/randy3k/collections/blob/master/README.md Shows basic deque (double-ended queue) operations: creating a deque, pushing an element to the right, pushing an element to the left, and popping from the right. Method chaining is supported. ```r dq <- deque() dq$push(1)$pushleft(2) dq$pop() ``` -------------------------------- ### Ordereddict Constructor Source: https://github.com/randy3k/collections/blob/master/docs/reference/OrderedDict.html Creates an ordered dictionary. It can be initialized with a list of items or keys. ```APIDOC ## Ordereddict Constructor ### Description Creates an ordered dictionary. It can be initialized with a list of items or keys. ### Signature Ordereddict(items = NULL, keys = NULL) ### Parameters * **items** (list) - a list of items * **keys** (list) - a list of keys, use `names(items)` if `NULL` ``` -------------------------------- ### Stack Methods Source: https://github.com/randy3k/collections/blob/master/docs/reference/stack.html Provides details on the methods available for interacting with a stack object. ```APIDOC ## Stack Methods ### Description These methods allow for manipulation and inspection of the stack. ### Methods - **push(item)**: Adds an item to the top of the stack. - **pop()**: Removes and returns the item from the top of the stack. - **peek()**: Returns the item from the top of the stack without removing it. - **clear()**: Removes all items from the stack. - **size()**: Returns the number of items in the stack. - **as_list()**: Converts the stack to a list. - **print()**: Prints the stack. ### Parameters - **item** (any R object) - The item to be added to the stack (for `push` method). ### Request Example ```R s <- stack() s$push("first") s$push("second") print(s$pop()) # second print(s$peek()) # first print(s$size()) # 1 ``` ### Response - **pop()**: Returns the removed item. - **peek()**: Returns the top item. - **size()**: Returns an integer representing the number of items. - **as_list()**: Returns a list. - **print()**: Returns NULL (invisibly). ``` -------------------------------- ### PriorityQueue Methods Source: https://github.com/randy3k/collections/blob/master/docs/reference/PriorityQueue.html Exposes various methods for interacting with the PriorityQueue, including adding items, removing items, clearing the queue, and checking its size. ```APIDOC ## PriorityQueue Methods ### Description Provides methods to manage and query the PriorityQueue. ### Methods * **$push(item, priority = 0)**: Adds an item to the queue with an optional priority. Higher priority values are processed first. * `item`: Any R object to be added. * `priority`: A real number representing the item's priority. Defaults to 0. * **$pop()**: Removes and returns the item with the highest priority from the queue. * **$clear()**: Removes all items from the queue. * **$size()**: Returns the number of items currently in the queue. * **$as_list()**: Converts the priority queue to a list. * **$[print]()**: Prints the priority queue. ``` -------------------------------- ### Create and Manipulate a Deque Source: https://github.com/randy3k/collections/blob/master/docs/reference/deque.html Demonstrates creating an empty deque, adding elements to the right and left, and removing elements from both ends. Note the order of operations and the resulting values after pops. ```R q <- deque() q$push("foo") q$push("bar") q$pushleft("baz") q$pop() # bar #> [1] "bar" q$popleft() # baz #> [1] "baz" ``` -------------------------------- ### Queue with NULL Values Source: https://context7.com/randy3k/collections/llms.txt Illustrates that NULL values can be stored in the queue and are handled correctly during pop operations. ```r # NULL values are supported q3 <- queue() q3$push(NULL)$push(NULL) q3$pop() # NULL q3$size() # [1] 1 (second NULL still in queue) ``` -------------------------------- ### deque() Source: https://github.com/randy3k/collections/blob/master/docs/reference/deque.html Creates a new double-ended queue. It can be initialized with an optional list of items. ```APIDOC ## deque() ### Description Creates a double ended queue. ### Usage ``` deque(items = NULL) ``` ### Arguments * `items` (list, optional) - A list of items to initialize the deque with. ``` -------------------------------- ### priority_queue Source: https://context7.com/randy3k/collections/llms.txt Creates a max-heap priority queue where items with higher priority values are popped first. Supports methods for pushing, popping, clearing, checking size, converting to a list, and printing. ```APIDOC ## `priority_queue(items = NULL, priorities = rep(0, length(items)))` — Max-Heap Priority Queue Creates a max-heap priority queue: `$pop()` always returns the item with the highest priority value. The default priority is `0`; higher numeric values pop first. Methods: `$push(item, priority = 0)`, `$pop()`, `$clear()`, `$size()`, `$as_list()`, `$print()`. ``` -------------------------------- ### Ordereddict Methods Source: https://github.com/randy3k/collections/blob/master/docs/reference/OrderedDict.html Exposes various methods for interacting with the ordered dictionary. ```APIDOC ## OrderedDict Methods ### Description Following methods are exposed for manipulating the ordered dictionary. ### Methods * `.set(key, value)`: Adds or updates an item in the dictionary. * `.get(key, default)`: Retrieves an item by key, returning a default value if not found. * `.remove(key)`: Removes an item from the dictionary by key. * `.pop(key, default)`: Removes and returns an item by key, with an optional default value. * `.popitem(last = TRUE)`: Removes and returns the last (or first if `last=FALSE`) item. * `.has(key)`: Checks if a key exists in the dictionary. * `.keys()`: Returns a list of all keys in the dictionary. * `.values()`: Returns a list of all values in the dictionary. * `.update(d)`: Updates the dictionary with items from another Ordereddict or OrdereddictL. * `.clear()`: Removes all items from the dictionary. * `.size()`: Returns the number of items in the dictionary. * `.as_list()`: Converts the ordered dictionary to a list, preserving order. * `.print()`: Prints the ordered dictionary. ### Parameters * `key`: scalar character, environment or function * `value`: any R object, value of the item * `default`: optional, the default value of an item if the key is not found * `d`: an Ordereddict or OrdereddictL ``` -------------------------------- ### Queue Source: https://github.com/randy3k/collections/blob/master/docs/reference/index.html Represents a Queue data structure (First-In, First-Out). ```APIDOC ## queue() ### Description Provides a Queue data structure. ### Method N/A (Function call) ### Endpoint N/A ### Parameters None explicitly documented. ### Request Example ```R queue() ``` ### Response #### Success Response Returns a queue object. ### Response Example ```R # Example output (conceptual) Queue object ``` ```