google / starlark-go

Starlark in Go: the Starlark configuration language, implemented in Go
BSD 3-Clause "New" or "Revised" License
2.31k stars 210 forks source link

FR: Support More Methods for type `set` #492

Open ohmyx opened 1 year ago

ohmyx commented 1 year ago

As per PYthon doc : https://docs.python.org/3.10/library/stdtypes.html#set-types-set-frozenset

The five methods should be added:

add(elem)
Add element elem to the set.

remove(elem)
Remove element elem from the set. Raises KeyError if elem is not contained in the set.

discard(elem)
Remove element elem from the set if it is present.

pop()
Remove and return an arbitrary element from the set. Raises KeyError if the set is empty.

clear()
Remove all elements from the set.

Now it's too hard to use, for example, add() can only be implemented via helper like:

def set_add(s, x):
    l = list(s)
    l.append(x)
    return set(l)
qms95 commented 1 year ago

+1 当前set太鸡肋了!

adonovan commented 1 year ago

These operations are all compatible with Python and consistent with starlark-go's notion of set, and they are useful but awkward or inefficient to implement in Starlark itself, so I would accept a PR to add all of these methods. (set is a starlark-go-specific extension, so there's no need for a proposal.)

SamWheating commented 1 year ago

I'm looking for something to work on, so I've started implementing this. Feel free to assign this issue to me and I'll try to have a PR open soon 👍

nihaobad commented 1 year ago

@SamWheating Thanks for your work!

Can you please add the following useful methods as well?

union()        -> a | b
intersection() -> a & b
difference()   -> a - b
symmetric_difference()  -> a ^ b

issubset()     -> a <= b
issuperset()   -> a >= b
adonovan commented 1 year ago

The |, &, ^ operators on sets are already supported, but the-, <=, and >= operators are missing. The union method is present but the others are missing. All seem like reasonable features to add.

ohmyx commented 1 year ago

The |, &, ^ operators on sets are already supported, but the-, <=, and >= operators are missing. The union method is present but the others are missing. All seem like reasonable features to add.

Yes. It would be nice to have those methods, 'cause the symbols are initially elusive in understanding. @adonovan

Welcome to Starlark (go.starlark.net)
>>> x = set([1,2,3])
>>> y = set([3,5,6])
>>> x & y
set([3])
>>> x | y
set([1, 2, 3, 5, 6])
>>> x - y
Traceback (most recent call last):
  <stdin>:1:3: in <expr>
Error: unknown binary op: set - set
>>> x ^ y
set([1, 2, 5, 6])
>>> x <= y
Traceback (most recent call last):
  <stdin>:1:3: in <expr>
Error: set <= set not implemented
>>> x >= y
Traceback (most recent call last):
  <stdin>:1:3: in <expr>
Error: set >= set not implemented
SamWheating commented 1 year ago

Good idea, I will add those functions as well as the infix operators in the next few days.