fsharp / fslang-suggestions

The place to make suggestions, discuss and vote on F# language and core library features
340 stars 21 forks source link

[Slice] Allow slice syntax to use instance `Slice` method instead of requiring `GetSlice` method #1317

Open xperiandri opened 8 months ago

xperiandri commented 8 months ago

I propose we convert slice syntax not only to GetSlice call but to Slice call that is now implemented by all collections

The existing way of approaching this problem in F# is implementing SRTP extension method

namespace System

open System.Runtime.CompilerServices

[<Extension>]
type SliceExtensions =

    [<Extension>]
    static member inline GetSlice<'c
            when 'c : (member Slice: int * int -> 'c)
            and  'c : (member Length: int)>
        (source: 'c, from: int option, ``to``: int option) =

        let from = from |> Option.defaultValue 0
        let ``to`` = ``to`` |> Option.defaultValue (source.Length - 1)
        source.Slice(from, ``to`` + 1 - from)

Pros and Cons

The advantages of making this adjustment to F# are all slicing available in C# will work in F#

The disadvantages of making this adjustment to F# are not exist

Extra information

Estimated cost (XS, S, M, L, XL, XXL): XS

Related suggestions:

Affidavit (please submit!)

Please tick these items by placing a cross in the box:

Please tick all that apply:

For Readers

If you would like to see this issue implemented, please click the :+1: emoji on this issue. These counts are used to generally order the suggestions by engagement.

smoothdeveloper commented 8 months ago

I know GetSlice is kind of fresh, is there a sense that now "the BCL team has decided the name", we could deprecate GetSlice through a warning, and have Slice instead?

It seems the "framework design guidelines" trend of everything being a bit verbose and explicit, "GetX", are past history, and the BCL design team is looking at C++ (https://en.cppreference.com/w/cpp/numeric/valarray/slice) for choosing identifiers more than those original guidelines.

Maybe that will help us making the same, if we face again "let's do transversal feature that carries a name into F# libraries" but can't wait for BCL team to decide, we can pick from C++ if the concept exists there and is applicable.

jwosty commented 6 months ago

I run into this most frequently with Span.

brianrourkeboll commented 2 months ago

Is there a good reason not to add support for Slice?

The only downsides I can think of are:

But otherwise it seems silly to make everyone write an extension method to use the BCL collections' built-in slicing capabilities, forever, when the compiler could just do it for them.

dsyme commented 2 months ago

I'll mark this as approved in principle. It should be possible define Slice and have the F# slicing syntax light up.

Equally the SRTP workaround is pretty good!