Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mutable dynamic arrays, heaps, and simple union find data structures #585

Merged
merged 13 commits into from
Jan 27, 2025
3 changes: 3 additions & 0 deletions examples/stdlib/acme.effekt
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import char
import dequeue
import effekt
import exception
import heap
import io
import io/console
import io/error
Expand All @@ -25,6 +26,7 @@ import process
import queue
import ref
import regex
import resizable_array
import result
import scanner
import seq
Expand All @@ -33,5 +35,6 @@ import stream
import string
import test
import tty
import union_find

def main() = ()
6 changes: 6 additions & 0 deletions examples/stdlib/heap/heap.check
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
HeapTests
✓ simple heap sort on integers

1 pass
0 fail
1 tests total
27 changes: 27 additions & 0 deletions examples/stdlib/heap/heap.effekt
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import heap
import test

def main() = {
suite("HeapTests", false) {
test("simple heap sort on integers") {
with on[OutOfBounds].default { assertTrue(false); <> };
val h = heap[Int](box { (x: Int, y: Int) =>
if (x < y) {
Less()
} else Greater() // hacky, should sometimes be Equal()
})
h.insert(12)
h.insert(10)
h.insert(7)
h.insert(11)
h.insert(14)
assert(h.deleteMin(), 7)
assert(h.deleteMin(), 10)
assert(h.deleteMin(), 11)
assert(h.deleteMin(), 12)
assert(h.deleteMin(), 14)
assert(h.size, 0)
}
};
()
}
6 changes: 6 additions & 0 deletions examples/stdlib/resizable_array/resizable_array.check
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
ResizableArrayTests
✓ usage as stack

1 pass
0 fail
1 tests total
32 changes: 32 additions & 0 deletions examples/stdlib/resizable_array/resizable_array.effekt
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import resizable_array
import test

def main() = {
suite("ResizableArrayTests", false) {
test("usage as stack") {
with on[OutOfBounds].default { assertTrue(false, "out of bounds") }
val a = resizableArray()
a.add(1)
a.add(1)
a.add(2)
a.add(3)
a.add(13)
a.add(21)
a.add(34)
a.add(55)
assert(a.popRight(), 55)
assert(a.popRight(), 34)
assert(a.popRight(), 21)
assert(a.popRight(), 13)
a.add(5)
a.add(8)
assert(a.popRight(), 8)
assert(a.popRight(), 5)
assert(a.popRight(), 3)
assert(a.popRight(), 2)
assert(a.popRight(), 1)
assert(a.popRight(), 1)
}
};
()
}
6 changes: 6 additions & 0 deletions examples/stdlib/union_find/union_find.check
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
UnionFindTests
✓ three elements

1 pass
0 fail
1 tests total
21 changes: 21 additions & 0 deletions examples/stdlib/union_find/union_find.effekt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import union_find
import test

def main() = {
suite("UnionFindTests", false) {
test("three elements") {
with on[MissingValue].default { assertTrue(false, "MissingValue exception") }
val u = unionFind()
val a = u.makeSet()
val b = u.makeSet()
val c = u.makeSet()
assert(u.find(a), a)
assert(u.find(b), b)
assert(u.find(c), c)
u.union(a,b)
assert(u.find(a), u.find(b))
assert(u.find(c), c)
}
};
()
}
103 changes: 103 additions & 0 deletions libraries/common/heap.effekt
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
module heap
import resizable_array

/// Resizable 2-ary min-heap, backed by a resizable array
/// `cmp` defines the ordering of elements
record Heap[T](rawContents: ResizableArray[T], cmp: (T, T) => Ordering at {})

/// Make a new Heap with the given comparison operation
def heap[T](cmp: (T,T) => Ordering at {}) =
Heap[T](resizableArray(), cmp)

/// Make a new Heap with the given comparison operation and initial capacity
def heap[T](cmp: (T,T) => Ordering at {}, capacity: Int) =
Heap[T](resizableArray(capacity), cmp)

namespace internal {
def left(idx: Int) = 2 * idx + 1
def right(idx: Int) = 2 * idx + 2
def parent(idx: Int) = (idx - 1) / 2

def bubbleUp[A](heap: Heap[A], idx: Int) = {
val arr = heap.rawContents
arr.boundsCheck(idx) // idx > parent(idx), parent(parent(idx)) etc

def go(idx: Int): Unit = {
if (idx > 0 and (heap.cmp)(arr.unsafeGet(parent(idx)), arr.unsafeGet(idx)) is Greater()) {
arr.unsafeSwap(parent(idx), idx)
go(parent(idx))
}
}
go(idx)
}
def sinkDown[A](heap: Heap[A], idx: Int) = {
val arr = heap.rawContents

def infixLt(x: A, y: A) = {
if ((heap.cmp)(x,y) is Less()) { true } else { false }
}

def go(idx: Int): Unit = {
if (right(idx) < arr.size) {
val v = arr.unsafeGet(idx)
val l = arr.unsafeGet(left(idx))
val r = arr.unsafeGet(right(idx))
if (l < v && r < v) {
// swap with the smaller one
if (l < r) {
arr.unsafeSwap(left(idx), idx)
go(left(idx))
} else {
arr.unsafeSwap(right(idx), idx)
go(right(idx))
}
} else if (l < v) {
arr.unsafeSwap(left(idx), idx)
go(left(idx))
} else if (r < v) {
arr.unsafeSwap(right(idx), idx)
go(right(idx))
}
} else if (left(idx) < arr.size) {
if (arr.unsafeGet(left(idx)) < arr.unsafeGet(idx)) {
arr.unsafeSwap(left(idx), idx)
go(left(idx))
}
} // else: we are at the bottom
}
go(idx)
}
}

/// Insert value into heap
///
/// O(log n) worst case if capacity suffices, O(1) average
def insert[T](heap: Heap[T], value: T): Unit = {
with on[OutOfBounds].panic();
val idx = heap.rawContents.add(value)
internal::bubbleUp(heap, idx)
}

/// find and return (but not remove) the minimal element in this heap
///
/// O(1)
def findMin[T](heap: Heap[T]): T / Exception[OutOfBounds] = {
heap.rawContents.get(0)
}

/// find and remove the minimal element in this heap
///
/// O(log n)
def deleteMin[T](heap: Heap[T]): T / Exception[OutOfBounds] = {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bike shed, in the comment you write "remove" but the function is called deleteMin. Some languages also call this operation pop (and insert then push):

https://doc.rust-lang.org/std/collections/struct.BinaryHeap.html

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I chose the names based on what https://en.wikipedia.org/wiki/Binary_heap calls the operations, but we can rename them - I don't have a strong opinion here.

val res = heap.rawContents.get(0)
heap.rawContents.unsafeSet(0, heap.rawContents.popRight())
internal::sinkDown(heap, 0)
res
}

/// Number of elements in the heap
///
/// O(1)
def size[T](heap: Heap[T]): Int = {
heap.rawContents.size
}
Loading
Loading