Skip to content

Commit

Permalink
Add items and contains to heapqueue (nim-lang#23296)
Browse files Browse the repository at this point in the history
The implementation of these functions are trivial yet they were missing
from the module.
  • Loading branch information
planetis-m authored Feb 9, 2024
1 parent befb383 commit c234a2a
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions lib/pure/collections/heapqueue.nim
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ runnableExamples:

import std/private/since

when defined(nimPreviewSlimSystem):
import std/assertions

type HeapQueue*[T] = object
## A heap queue, commonly known as a priority queue.
data: seq[T]
Expand All @@ -73,6 +76,13 @@ proc `[]`*[T](heap: HeapQueue[T], i: Natural): lent T {.inline.} =
## Accesses the i-th element of `heap`.
heap.data[i]

iterator items*[T](heap: HeapQueue[T]): lent T {.inline, since: (2, 1, 1).} =
## Iterates over each item of `heap`.
let L = len(heap)
for i in 0 .. high(heap.data):
yield heap.data[i]
assert(len(heap) == L, "the length of the HeapQueue changed while iterating over it")

proc heapCmp[T](x, y: T): bool {.inline.} = x < y

proc siftup[T](heap: var HeapQueue[T], startpos, p: int) =
Expand Down Expand Up @@ -178,6 +188,11 @@ proc find*[T](heap: HeapQueue[T], x: T): int {.since: (1, 3).} =
for i in 0 ..< heap.len:
if heap[i] == x: return i

proc contains*[T](heap: HeapQueue[T], x: T): bool {.since: (2, 1, 1).} =
## Returns true if `x` is in `heap` or false if not found. This is a shortcut
## for `find(heap, x) >= 0`.
result = find(heap, x) >= 0

proc del*[T](heap: var HeapQueue[T], index: Natural) =
## Removes the element at `index` from `heap`, maintaining the heap invariant.
runnableExamples:
Expand Down

0 comments on commit c234a2a

Please sign in to comment.