Skip to content

byref and inref for loops #1453

@Happypig375

Description

@Happypig375

I propose we allow this:

let zero (span : System.Span<int>) =
    for item : int byref in span do item <- 0
let useInref (span : System.ReadOnlySpan<int>) =
    for item : int inref in span do System.ReadOnlySpan (&item)

This is the equivalent of C#'s

If the enumerator's Current property returns a reference return value (ref T where T is the type of a collection element), you can declare an iteration variable with the ref or ref readonly modifier

Since byref/inref/outref cannot be an inferred type from type inference, this should not be a breaking change to type inference.

The existing way of approaching this problem in F# is to work around the absence of this feature entirely, for example using integer iterators, which is verbose and not applicable to collections that are not randomly indexable. Alternatively, writing manual while loops with direct invocation of Current and MoveNext which is more error-prone than for loops.

Pros and Cons

The advantages of making this adjustment to F# are

  1. C# parity
  2. Conciseness
  3. Encouraging writing performant code that is safe

The disadvantage of making this adjustment to F# is implementation complexity.

Extra information

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

Related suggestions: (put links to related suggestions here)

Affidavit (please submit!)

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

  • This is not a question (e.g. like one you might ask on StackOverflow) and I have searched StackOverflow for discussions of this issue
  • This is a language change and not purely a tooling change (e.g. compiler bug, editor support, warning/error messages, new warning, non-breaking optimisation) belonging to the compiler and tooling repository
  • This is not something which has obviously "already been decided" in previous versions of F#. If you're questioning a fundamental design decision that has obviously already been taken (e.g. "Make F# untyped") then please don't submit it
  • I have searched both open and closed suggestions on this site and believe this is not a duplicate

Please tick all that apply:

  • This is not a breaking change to the F# language design
  • I or my company would be willing to help implement and/or test this

For Readers

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions