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

Differentiate unconstrained lists vs. orderable? #1

Open
andig opened this issue Dec 12, 2022 · 1 comment
Open

Differentiate unconstrained lists vs. orderable? #1

andig opened this issue Dec 12, 2022 · 1 comment

Comments

@andig
Copy link

andig commented Dec 12, 2022

Coming here emirpasic/gods#179 looking for a generic Queue (based on generic List). The current List implementations are constrained by orderable to allow for Contains and IndexOf (maybe more). It would be nice if the orderable Properties could be optional, i.e. part of a different type (OrderableList?). Otherwise, the lists become useless for queues of uncomparable types like e.g. func().

@andig
Copy link
Author

andig commented Dec 12, 2022

I did a quick prototype and something like this seems to work:

// List interface that all lists implement
type List[T any] interface {
	Get(index int) (T, bool)
	Remove(index int)
	Add(values ...T)
	Sort(comparator utils.Comparator)
	Swap(index1, index2 int)
	Insert(index int, values ...T)
	Set(index int, value T)

	// Contains(values ...T) bool
	// IndexOf(value T) int

	containers.Container[T]
	// Empty() bool
	// Size() int
	// Clear()
	// Values() []T
	// String() string
}

type ComparableList[T comparable] interface {
	List[T]
	Contains(values ...T) bool
	IndexOf(value T) int
}

with the actual comparable type broken out in the same folder:

// ComparableList holds the elements in a slice
type ComparableList[T comparable] struct {
	List[T]
}

// NewComparable instantiates a new list and adds the passed values, if any, to the list
func NewComparable[T comparable](values ...T) *ComparableList[T] {
	list := &ComparableList[T]{}
	if len(values) > 0 {
		list.Add(values...)
	}
	return list
}

This breaks the original lists.List interface but keeps the usability more general without resorting to use of reflection.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant