Logo

Programming-Idioms

  • Pascal
  • Go

Idiom #118 List to set

Create the set y from the list x.
x may contain duplicates. y is unordered and has no repeated values.

Turning the list [a,b,c,b] into the set {c,a,b}
func sliceToSet[T comparable](x []T) map[T]struct{} {
	y := make(map[T]struct{}, len(x))
	for _, v := range x {
		y[v] = struct{}{}
	}
	return y
}

sliceToSet is generic. Its type parameter T has a constraint: must be comparable with ==.
y := make(map[T]struct{}, len(x))
for _, v := range x {
	y[v] = struct{}{}
}

Iterate to add each item to the map.
T is the type of the items.
for i := Low(X) to High(X) do Include(Y,X[i]);

Sets never have repeated values in Pascal. Adding a value that already is in the set leaves the set unchanged (and does not raise any error).
(def y (set x))

New implementation...