A colleague reviewed my code and asked why I used the following template:
type MyType() = member this.TestMethod() = let a = 1 // do some work let a = 2 // another value of a from the work result ()
I told him that this is a bad model, and I intend to use let mutable a = ... But then he asked why there are such consistent bindings in the F # class at all, while this is not possible in the module or the .fsx file? In essence, we mutate a constant value!
I replied that in the module or in the .fsx file, the let binding becomes a static method, so directly binding with the same name conflicts in the same way as two properties of the class with the same name. But I do not know why this is possible inside the method!
In C #, I found scoping variables useful, especially in unit tests, when I want to compose several different values for test cases by simply copying code fragments:
{ var a = 1; Assert.IsTrue(a < 2); } { var a = 42; Assert.AreEqual(42, a); }
In F #, we could not only repeat the same binding bindings, but change immutable to mutable, and then mutate it later in the usual way:
type MyType() = member this.TestMethod() = let a = 1
Why are we allowed to repeat binding bindings in F # methods? How to explain this to a person who is new to F # and asked: "What is an immutable variable and why am I mutating it?"
Personally, I’m interested in what design options and compromises were made to allow this? It’s convenient for me when various areas of visibility are easily detected, for example. when the variable is in the constructor, and then we redefine it in the body or define a new binding inside the for / while loops. But two consecutive bindings on the same level are somewhat contrary to intuition. It seems to me that I should mentally add in at the end of each line, as in the detailed syntax, in order to explain the scope, so those virtual in look like C # {}