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

喜欢而已 提交于 2019-12-19 17:32:35

问题


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 .


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/24389553/is-there-a-way-to-have-warnings-for-shadowing-values-in-f-in-visual-studio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!