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

proposal: container/heap generic example #61993

Closed
rossb83 opened this issue Aug 13, 2023 · 2 comments
Closed

proposal: container/heap generic example #61993

rossb83 opened this issue Aug 13, 2023 · 2 comments

Comments

@rossb83
Copy link

rossb83 commented Aug 13, 2023

Now that generics are sorted out the documentation example priority queue here https://pkg.go.dev/container/heap should include the use of generics like below

type PriorityQueue[K comparable, P cmp.Ordered] []*Item[K, P]

type Item[K comparable, P cmp.Ordered] struct {
	value    K
	priority P
	index    int
}

func (pq PriorityQueue[_, _]) Len() int {
	return len(pq)
}

func (pq PriorityQueue[_, _]) Less(i, j int) bool {
	return pq[i].priority < pq[j].priority
}

func (pq PriorityQueue[_, _]) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	pq[i].index = i
	pq[j].index = j
}

func (pq *PriorityQueue[K, P]) Push(x any) {
	n := len(*pq)
	item := x.(*Item[K, P])
	item.index = n
	*pq = append(*pq, item)
}

func (pq *PriorityQueue[_, _]) Pop() any {
	old := *pq
	n := len(old)
	item := old[n-1]
	old[n-1] = nil  // avoid memory leak
	item.index = -1 // for safety
	*pq = old[0 : n-1]
	return item
}

Beyond this I feel there is a lot of machinery required to implement the heap interface (like above) and wonder if any work can/should be done to make this simpler.

@gopherbot gopherbot added this to the Proposal milestone Aug 13, 2023
@cespare
Copy link
Contributor

cespare commented Aug 13, 2023

Instead of adding documentation, we should add an implementation (see #47632).

@seankhliao
Copy link
Member

Duplicate of #47632

@seankhliao seankhliao marked this as a duplicate of #47632 Aug 13, 2023
@seankhliao seankhliao closed this as not planned Won't fix, can't repro, duplicate, stale Aug 13, 2023
@golang golang locked and limited conversation to collaborators Aug 12, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

4 participants