FSharpLint icon indicating copy to clipboard operation
FSharpLint copied to clipboard

Structs: DUs and active patterns that have no fields or only simple sturcts should also be structs

Open Thorium opened this issue 11 months ago • 2 comments

I'm stealing the great idea from @nojaf and adding it here as possible development as well. :-)

From FSharp.Core 6.0.1 onwards (F# 6):

A DU without any fields should be a struct:

[<Struct>]
type MyType =
| A
| B

Enums are fine, and this is a struct already:

type MyType =
| A = 1
| B = 2

Enums with simple fields like only boolean, int, Guid or struct could be also recommended to be structs, but that should be configurable, because that needs the name for the field, and changes may be a breaking change for existing API:

[<Struct>]
type MyType =
| A of a: int 
| B of b: struct(bool*bool)

Partial active pattern that returns empty (), boolean, guid or int, should also be marked as [<return: Struct>] and use ValueOption instead of Option:

[<return: Struct>]
let (|MyThing|_|) x =
   if x then ValueSome()
   else ValueNone

This comes from conversation in here: https://github.com/fsprojects/FSharp.Formatting/pull/906

Thorium avatar Mar 15 '24 16:03 Thorium

So this would be a rule whose purpose is optimization? (speed? memory?)

knocte avatar Mar 15 '24 17:03 knocte

Yes, both. Similarly like testing IEnumerable isEmpty is optimization over "length > 0".

Thorium avatar Mar 15 '24 18:03 Thorium

I'm closing this because this is already done in ionide-analyzers project. Over time that will already improve general F# code-bases on a level appropriate, there is no point of doing double amount of work implementing it here.

Thorium avatar Apr 02 '24 06:04 Thorium