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
(thinking…)
Sign in with: facebook google
Signed in as (Sign out)
You have left! (?) (thinking…)
Gustavo Guerra shared this idea  ·   ·  Flag idea as inappropriate…  ·  Admin →

5 comments

Sign in
(thinking…)
Sign in with: facebook google
Signed in as (Sign out)
Submitting...
  • Gusty commented  ·   ·  Flag as inappropriate

    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 Gibson commented  ·   ·  Flag as inappropriate

    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?

  • Goswin commented  ·   ·  Flag as inappropriate

    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]

F# Language

Feedback and Knowledge Base