diff --git a/changelog.md b/changelog.md index 7d1217f97..5a439285c 100644 --- a/changelog.md +++ b/changelog.md @@ -201,6 +201,10 @@ - Add `readLines(p: Process)` to `osproc` module for `startProcess` convenience. +- Added `heapqueue.toHeapQueue`, which creates a HeapQueue from an openArray. + The usage is similar to procs such as `sets.toHashSet` and `tables.toTable`. + Previously, it was necessary to create an empty HeapQueue and add items + manually. - Added `intsets.toIntSet`, which creates an IntSet from an openArray. The usage is similar to procs such as `sets.toHashSet` and `tables.toTable`. Previously, it was necessary to create an empty IntSet and add items manually. diff --git a/lib/pure/collections/heapqueue.nim b/lib/pure/collections/heapqueue.nim index c2952cf1b..ca0666651 100644 --- a/lib/pure/collections/heapqueue.nim +++ b/lib/pure/collections/heapqueue.nim @@ -58,6 +58,9 @@ type HeapQueue*[T] = object proc initHeapQueue*[T](): HeapQueue[T] = ## Create a new empty heap. + ## + ## See also: + ## * `toHeapQueue proc <#toHeapQueue,openArray[T]>`_ discard proc len*[T](heap: HeapQueue[T]): int {.inline.} = @@ -115,6 +118,20 @@ proc push*[T](heap: var HeapQueue[T], item: T) = heap.data.add(item) siftdown(heap, 0, len(heap)-1) +proc toHeapQueue*[T](x: openArray[T]): HeapQueue[T] {.since: (1, 3).} = + ## Creates a new HeapQueue that contains the elements of `x`. + ## + ## See also: + ## * `initHeapQueue proc <#initHeapQueue>`_ + runnableExamples: + var heap = toHeapQueue([9, 5, 8]) + assert heap.pop() == 5 + assert heap[0] == 8 + + result = initHeapQueue[T]() + for item in items(x): + result.push(item) + proc pop*[T](heap: var HeapQueue[T]): T = ## Pop and return the smallest item from `heap`, ## maintaining the heap invariant. @@ -195,6 +212,7 @@ when isMainModule: let data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0] for item in data: push(heap, item) + doAssert(heap == data.toHeapQueue) doAssert(heap[0] == 0) doAssert(heap.toSortedSeq == @[0, 1, 2, 3, 4, 5, 6, 7, 8, 9])