Which function is called for the expression "some string".[3 .. 7] in F#?

Viewed 68

Just found out that with f# sub-strings can be defined as slices:

let s = "the quick brown fox"
s.[4..8] // returns a string!
val it : string = "quick"

The remarkable thing is that the slice expression returns a string, not a char collection. I thought that strings in F# core implement GetSlice, which would return a string, but that is not the case:

https://github.com/dotnet/fsharp/blob/main/src/fsharp/FSharp.Core/string.fs

So I really wonder what happens here? Which function is called for the slice operation?

1 Answers

The typechecker looks for the syntactical form of the slice here: https://github.com/dotnet/fsharp/blob/main/src/fsharp/CheckExpressions.fs#L6351

Which ultimately leads to a call to GetStringSlice being emitted: https://github.com/dotnet/fsharp/blob/d5cc1167df4201b7cf9adf4b6b71e9494be556f4/src/fsharp/FSharp.Core/prim-types.fs#L6039

The path is typechecker --> fsharp.core stuff --> chain of calls until emission.

So, why not just a type extension on String in FSharp.Core? Dunno. It's some decision made long ago. Sometimes the compiler has these paths that hop around a bit.

Related