F#, assignment operator vs set operator

前端 未结 2 1240
一整个雨季
一整个雨季 2020-12-19 23:35

I have started with F# and some code structure wonder me. For example:

I have next code:

let mutable s = 10
s <- 1 + s
printf \"%i\" s


        
相关标签:
2条回答
  • 2020-12-20 00:26

    The code

    s=1+s
    

    will does not modify s - the equivalent C# is

    s==1+s
    

    which just returns false

    In fact, the compiler should have issued a warning on that line about a value being unused.

    The = operator just does an equality check - it does not assign any values.

    0 讨论(0)
  • 2020-12-20 00:39

    To answer your second question -

    Why didn't I get a error? Is s = 1 + s just ignored? Why? I didn't get any error in the output.

    The reason for this is that F# distinguishes between top-level scope in a script file and local scope. When you are in a script file (*.fsx file in Visual Studio or inside Try F#), then you probably want to write a sequence of expressions (that may return a value) and execute them interactively one by one. This means that when you write s = 1 + s on one line, this is not an error because you can evaluate the line (select it and hit Ctrl+Enter or Alt+Enter) and see the result in the interactive output.

    However, when this appears inside a function (or in other local scope where you are not expected to evaluate it interactively), you get a warning. The easiest way to see is to create a local scope using do (and this works in Try F# too):

    do
      let mutable s = 10
      s = 1 + s           // Warning: This expression should have type 'unit', 
                          //    but has type 'bool'. If assigning to a property 
                          //    use the syntax 'obj.Prop <- expr'.
      printf "%i" s
    
    0 讨论(0)
提交回复
热议问题