Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to have warnings for shadowing values in F# in Visual Studio?

To me shadowing of existing values like described in:

Shadowing and Nested function
immutable in F#
f# duplicate definition
FSharp for fun and profit comment

seems to be going against the notion of immutability and type safety that makes F# so strong. Shadowing in F# works different than in C#. It just took me quite some time to find out that a bug in my code was due to unintentional shadowing of a name within the same scope. Is there a way to have compiler warnings for shadowing values in VS?

I know that in some cases it can be useful. for example for Checked Aritmetics .

like image 316
Goswin Rothenthal Avatar asked Jun 24 '14 14:06

Goswin Rothenthal


2 Answers

One place I use shadowing is when resolving an optional parameter to a default value if no value was supplied.

member x.Foo(?myFlag: bool) =
    let myFlag = defaultArg myFlag false
    ...

Also F# Interactive, the way it's implemented now, would be pretty much completely non-functional if we didn't have shadowing.

like image 154
Joel Mueller Avatar answered Sep 28 '22 08:09

Joel Mueller


Shadowing has pros and cons. I too have encountered bugs due to fat-fingered shadowing efforts. On the plus side, it can help keep your variable space clean as @JoelMueller pointed out.

Shadowing bugs are fundamentally different than mutable variable bugs. They are of the typo variety. They are much easier to analyze: historical information loss is minimized to lexicographical context versus environmental context. That is, with shadowing, you can always cleanly trace the value of a binding through mental stack unrolling, whereas variable mutations create what are essentially gotos (jump to address).

Practically, shadowing still eliminates whole classes of bugs. You won't encounter any "spooky actions from a distance". Namely, you won't run into issues with variables captured in closures or variables being modified in nested scopes relative to the current scope.

like image 25
Stephen Swensen Avatar answered Sep 28 '22 09:09

Stephen Swensen