Skip to content

Feature Request: Support +/-/+=/-= operators for all IList types #13152

Closed

Description

Summary of the new feature/enhancement

Using modern types such as List/OrderedList/SortedList/etc. is becoming more common for performance reasons, but the array manipulation operators reconstruct these as [Object[]] which is not ideal for many already discussed reasons, and using other syntax such as .Add() is awkward especially for newer Powershell Users. Dictionary does not have this issue as the property assignment operators work fine.

I propose that, if a class implements IList and does not have op_Addition or op_Subtraction already defined, that the operators will use the standard IList Add and Remove methods to manipulate the array and preserve it rather than recasting all the contents into a new [Object[]].

This will allow users who want to use more advanced types for performance to be able to do so without breaking any behavior of @() syntax or normal powershell user experience.

NOTE: #5643 proposed a lot of syntactic sugar around lists or replacing the default type with lists. This Feature Request is smaller in scope but compatible and is less likely to cause breaking regressions.

Potential Breaking Changes

  1. Scripts that anticipate the existing behavior of casting to an [Object[]] and work around it could break, but it would have to be very specific and very rare edge case, for instance something that recasts it to a list would simply just cast a list to a list and not break. Could be controlled with a preference variable

EDITS

  1. Narrowed scope to just += and -= operators due to Patrick Meinecke (@SeeminglyScience)'s valid concerns

Activity

  1. added
    Issue-Enhancement
    on Jul 10, 2020
  2. changed the title [-]Feature Request: Support +/-/+=/-= operators for all IEnumerable types[/-] [+]Feature Request: Support +/-/+=/-= operators for all IList types[/+] on Jul 10, 2020
  3. SeeminglyScience commented on Jul 10, 2020

    @SeeminglyScience
    Contributor

    It's worth noting that this would be the only instance afaik where the += operator would actually mutate the object on the LHS instead of creating a new object and assigning it.

    I don't know if that's necessarily a good reason to object, I'm on the fence about it personally.

  4. JustinGrote commented on Jul 10, 2020

    @JustinGrote
    ContributorAuthor

    Patrick Meinecke (@SeeminglyScience) well you could always type the result to [Object[]] if you want to preserve the existing behavior for wahtever reason :)

  5. SeeminglyScience commented on Jul 10, 2020

    @SeeminglyScience
    Contributor

    I mean from the perspective of the language this would be the only instance where the LHS actually gets mutated. It's a little inconsistent since it's mostly syntactic sugar for $a = $a + $b. Also how would this interact with variable write breakpoints?

  6. vexx32 commented on Jul 10, 2020

    @vexx32
    Collaborator

    It'd be similar to what I'm doing here: #12930

    At least in terms of effectively mutating the LHS. We can pretty much check for IList, then do a check for IsFixedSize -- if that's true, we just fallback to existing behaviour. If it's not, we call Add() and attempt to insert the items.

    I would prefer not to have to deal with merge conflicts in those code paths though, the very thought is painful 😭, so if we can get that either merged or rejected first..... 🙏

  7. JustinGrote commented on Jul 10, 2020

    @JustinGrote
    ContributorAuthor

    I agree probably should block on #12930, good call on checking for IsFixedSize

  8. vexx32 commented on Jul 10, 2020

    @vexx32
    Collaborator

    There's some surrounding discussion of this in #5643 as well, it seems.

  9. SeeminglyScience commented on Jul 10, 2020

    @SeeminglyScience
    Contributor

    It'd be similar to what I'm doing here: #12930

    That still mostly fits with the existing $a = $a + $b rules. Only difference is with an event the actual value of $a is hidden from the caller. At the end of the day it's still usually $delegate1 = $delegate1 + $delegate2. Also nothing is mutated here, if the event implementer holds onto a copy of the original delegate, it'll still be that original delegate.

    At least in terms of effectively mutating the LHS. We can pretty much check for IList, then do a check for IsFixedSize -- if that's true, we just fallback to existing behaviour. If it's not, we call Add() and attempt to insert the items.

    Right but what I'm saying is that all existing support for addition adds two things together and returns a new object. Even the existing array support basically does $array = $array + [object[]]$item.

  10. JustinGrote commented on Jul 10, 2020

    @JustinGrote
    ContributorAuthor

    There's some surrounding discussion of this in #5643 as well, it seems.
    I referenced this in my original post, the goal here was to narrow the scope to just the operators, that post has gone into changing away from Array as the default.

  11. SeeminglyScience commented on Jul 10, 2020

    @SeeminglyScience
    Contributor

    Just so it's crystal clear what I mean, here's an example:

    $a = 1..10
    $b = $a
    $b += 11
    
    $a.Length # 10
    $b.Length # 11
    
    $a = [System.Collections.Generic.List[int]](1..10)
    $b = $a
    # What `$b += 11` would translate to
    $b.Add(11)
    
    $a.Count # 11
    $b.Count # 11

    The += syntax does not currently imply that the LHS will be mutated. I understand that the mutation is the point, that's what makes it faster. That said, mutation isn't free in terms of design. If you don't know you're mutating the LHS that could end up being just as problematic in the long term. Calling List<>.Add explicitly makes it very clear what's happening.

  12. JustinGrote commented on Jul 10, 2020

    @JustinGrote
    ContributorAuthor

    Patrick Meinecke (@SeeminglyScience) sure, totally get your point, I'm just trying to envision a scenario where if your logical flow is that you want a new array but preserve the old array and this is the syntax you would be using vs. just creating a new array.
    E.g. why would you do

    $a = 1..10
    $b = $a
    $b += 11

    instead of

    $a = 1..10
    $b = $a + 11

    and

    $a = 1..10
    $a += 11

    From just a logical standpoint, the fact that $a is still associated to $b because you did $a = $b is a side effect that you explicity called out, so I think you would know that it's doing it. Regardless, still not a problem that I think documentation wouldn't solve, it wouldn't be a completely new phenomenom in Powershell (e.g. lots of commands/etc. act differently depending on if you are passing a string vs. an object vs. a hashtable, etc.

    EDIT: I can see a case for $b = $a + 11 still returning a brand new object[] to be important, as one reasonably may not expect that $a would change as a result of this operation, maybe the scope should be narrowed to specifically the += and -= operators only.

  13. mklement0 commented on Jul 10, 2020

    @mklement0
    Contributor

    Justin Grote (@JustinGrote), this looks what I've originally proposed in #5805 (except for the - / -= part), but then PetSerAl raised valid concerns, similar to Patrick Meinecke (@SeeminglyScience)'s - the relevant part of the discussion starts at #5805 (comment)

  14. JustinGrote commented on Jul 10, 2020

    @JustinGrote
    ContributorAuthor

    Michael Klement (@mklement0) agreed, and what is in that issue is close enough in scope to this one that I'm going to close it as a dupe of that one.

    Closing in favor of continued #5805 discussion

  15. SeeminglyScience commented on Jul 10, 2020

    @SeeminglyScience
    Contributor

    I'm just trying to envision a scenario where if your logical flow is that you want a new array but preserve the old array and this is the syntax you would be using vs. just creating a new array.

    So mutation is most problematic when it comes to arguments. Here's an example of where things can go poorly:

    using namespace System.Collections.Generic
    
    function Invoke-SomeExecutable {
        param([List[string]] $ArgumentList)
        end {
            if ($ArgumentList[-1] -ne '/silent') {
                # Mutates the *caller's* copy of `$ArgumentList`
                $ArgumentList.Add('/silent')
            }
    
            # The real line would be something like:
            # & something.exe @ArgumentList
            Write-Host ($ArgumentList -join ' ')
        }
    }
    
    # Pretend this was built iteratively based on conditions to justify it being a list
    $commandLineArgs = [List[string]]('/computer', 'servername')
    $serverList = 1..5 | ForEach-Object { "DC$_" }
    foreach ($server in $serverList) {
        $commandLineArgs[-1] = $server
        Invoke-SomeExecutable $commandLineArgs
    }

    which returns

    /computer DC1 /silent
    /computer DC1 DC2 /silent
    /computer DC1 DC2 DC3 /silent
    /computer DC1 DC2 DC3 DC4 /silent
    /computer DC1 DC2 DC3 DC4 DC5 /silent
    

    E.g. why would you do

    $a = 1..10
    $b = $a
    $b += 11

    instead of

    $a = 1..10
    $b = $a + 11

    What would that example do though? If $a was a List<>, what would $b contain? Would it be
    the same list as $a (if so the same issue occurs) or would it be $null because List<>.Add has a void return?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-Enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions