I suggest we ...

Allow negative indices in indexing and slicing like python

Example: permit usage of a.[..-2] instead of a.[..a.Length-1]
The compiler could just do that conversion behind the scenes, so it would work with existing types that have custom indexing and slicing

39 votes
Vote
Sign in
Check!
(thinking…)
Reset
or sign in with
  • facebook
  • google
    Password icon
    I agree to the terms of service
    Signed in as (Sign out)
    You have left! (?) (thinking…)
    Gustavo GuerraGustavo Guerra shared this idea  ·   ·  Admin →

    5 comments

    Sign in
    Check!
    (thinking…)
    Reset
    or sign in with
    • facebook
    • google
      Password icon
      I agree to the terms of service
      Signed in as (Sign out)
      Submitting...
      • GustyGusty commented  · 

        I like it. FSharpPlus had that feature longtime:(https://github.com/gmpl/FSharpPlus/blob/0f0550000077cb9da3f340612a84911e92c1a790/FSharpPlus/Extensions.fs#L49)

        note that the GetSlice there support also negatives at the beginning of the string.

        But now I see that in F#4.0 it doesn't work anymore since GetSlice was added in the F# core (without the negatives) and shadows the method in F#+ so if this feature is not accepted an option would be to avoid shadowing those functions further defined in Libraries.
        This way everybody is free to decide to use negative indexing by using a library or writing an extension method.

      • Richard GibsonRichard Gibson commented  · 

        I remember this discussion coming up in CoffeeScript and it's surprisingly hard to do when you involve variables. For example:

        arr.[..x] // Should the compiler insert a check to see if x is negative?

      • GoswinGoswin commented  · 

        I am not sure if this schould be default.
        I am doing this with an extension member:

        let inline getNegIndex i len =
        let j = if i<0 then len + i else i
        if j<0 || j >= len then failwithf "Cannot get index %d from %d items (for given negative index %d ) " j len i
        else j

        type ``[]``<'T> with
        member inline arr.GetItemNeg i = arr.[getNegIndex i arr.Length]

      • Kit EasonKit Eason commented  · 

        This would be so freakin' useful in the code I am writing right now!

      F# Language

      Feedback and Knowledge Base