ballerina-lang
ballerina-lang copied to clipboard
Add logic to support `pop()` and `remove()` operations for tuples at runtime
Purpose
All the functionality of arrays should be present for tuples as tuples are a subtype of arrays. (https://github.com/ballerina-platform/ballerina-lang/issues/26820) Currently the
pop()andremove()operations are not supported at runtime and the proposed changes will add the necessary checks and logic to implement those operations.
Fixes #42954
Approach
Both remove() and pop() involve removing an element from the tuple. In remove, the removal can be from a selected index while in pop it has to be the last element of the tuple. The definitions for both methods are as follows.
# Removes a member of an array.
#
# + arr - the array
# + index - index of member to be removed from `arr`
# + return - the member of `arr` that was at `index`
# This removes the member of `arr` with index `index` and returns it.
# It panics if there is no such member.
public isolated function remove(Type[] arr, int index) returns Type = external;
# Removes and returns the last member of an array.
# The array must not be empty.
#
# + arr - the array
# + return - removed member
public isolated function pop(Type[] arr) returns Type = external;
Since shift() involves removing the first element of the tuple, we should be able to tweak and reuse the logic and checks used for that in both pop and remove. Once an element is removed from a particular location, the members after that location should be moved to fill the empty spot. This rearrangement will have to satisfy inherent type properties of the tuple as discussed in the shift() operation (refer https://github.com/ballerina-platform/ballerina-lang/pull/42815). Instead of checking all the members for matching inherent type, we only need to check elements after the removed element.
Remarks
This PR is contributing to https://github.com/ballerina-platform/ballerina-lang/issues/41431 Related issues and PRs: https://github.com/ballerina-platform/ballerina-spec/issues/731, https://github.com/ballerina-platform/ballerina-lang/issues/26820, https://github.com/ballerina-platform/ballerina-lang/issues/26843, https://github.com/ballerina-platform/ballerina-spec/issues/474, https://github.com/ballerina-platform/ballerina-lang/pull/22318
Check List
- [x] Read the Contributing Guide
- [ ] Updated Change Log
- [ ] Checked Tooling Support (#<Issue Number>)
- [ ] Added necessary tests
- [x] Unit Tests
- [ ] Spec Conformance Tests
- [ ] Integration Tests
- [ ] Ballerina By Example Tests
- [ ] Increased Test Coverage
- [ ] Added necessary documentation
- [ ] API documentation
- [ ] Module documentation in Module.md files
- [ ] Ballerina By Examples