File: set.go

package info (click to toggle)
golang-github-nlpodyssey-gopickle 0.3.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 732 kB
  • sloc: python: 32; makefile: 5
file content (54 lines) | stat: -rw-r--r-- 1,338 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Copyright 2020 NLP Odyssey Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package types

// SetAdder is implemented by any value that exhibits a set-like behaviour,
// allowing arbitrary values to be added.
type SetAdder interface {
	Add(v interface{})
}

// Set represents a Python "set" (builtin type).
//
// It is implemented in Go as a map with empty struct values; the actual set
// of generic "interface{}" items is thus represented by all the keys.
type Set map[interface{}]setEmptyStruct

var _ SetAdder = &Set{}

type setEmptyStruct struct{}

// NewSet makes and returns a new empty Set.
func NewSet() *Set {
	s := make(Set, 4)
	return &s
}

// NewSetFromSlice makes and returns a new Set initialized with the elements
// of the given slice.
func NewSetFromSlice(slice []interface{}) *Set {
	s := make(Set, len(slice))
	for _, item := range slice {
		s[item] = setEmptyStruct{}
	}
	return &s
}

// Len returns the length of the Set.
func (s *Set) Len() int {
	return len(*s)
}

// Add adds one element to the Set.
func (s *Set) Add(v interface{}) {
	(*s)[v] = setEmptyStruct{}
}

// Has returns whether the given value is present in the Set (true)
// or not (false).
func (s *Set) Has(v interface{}) bool {
	_, ok := (*s)[v]
	return ok
}