yagods icon indicating copy to clipboard operation
yagods copied to clipboard

Differentiate unconstrained lists vs. orderable?

Open andig opened this issue 3 years ago • 1 comments

Coming here https://github.com/emirpasic/gods/issues/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 avatar Dec 12 '22 09:12 andig

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.

andig avatar Dec 12 '22 10:12 andig