lcompilers / lpython

Python compiler
https://lpython.org/
Other
1.5k stars 158 forks source link

Add an implementation of `set.discard(elem)` #2629

Closed kmr-srbh closed 6 months ago

kmr-srbh commented 6 months ago

The official Python documentation describes set.discard(elem) as:

Remove element elem from the set if it is present.

and set.remove(elem) as:

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

Hence, it is obvious that both the functions do the same work, but differ only with throwing an error for an absent key. As we already had the infrastructure for set.remove, it was easy to base and implement set.discard on top of that.

The idea is simple - utilize the same back-end function, but do not throw an error for set.discard.

Working

from lpython import i32

my_set: set[i32] = {1, 2, 3, 4}
my_set.discard(1)
my_set.remove(1)
(base) saurabh-kumar@Awadh:~/Projects/System/lpython$ ./src/bin/lpython ./examples/example.py
KeyError: The set does not contain the specified element

The KeyError for set.remove proves the normal working of set.discard.

Handling KeyError

set.discard

from lpython import i32

my_set: set[i32] = {1, 2, 3, 4}
my_set.discard(100012345678901234567890)
(base) saurabh-kumar@Awadh:~/Projects/System/lpython$ ./src/bin/lpython ./examples/example.py
(base) saurabh-kumar@Awadh:~/Projects/System/lpython$ 

set.remove

from lpython import i32

my_set: set[i32] = {1, 2, 3, 4}
my_set.remove(100012345678901234567890)
(base) saurabh-kumar@Awadh:~/Projects/System/lpython$ ./src/bin/lpython ./examples/example.py
KeyError: The set does not contain the specified element
kmr-srbh commented 6 months ago

It looks good to me. Thanks for this. Please resolve the conflicts and I will take a look again.

Sure @Shaikh-Ubaid! These are due to the latest additions to main which made changes to the intrinsic function files. I am making the changes.

kmr-srbh commented 6 months ago

This is getting difficult to resolve as new files were added. It would be easier to open a new PR.