F # confusing output

I am starting F #. I ran this code:

let printMsg() = let msg = "Important" printfn "%s" msg let innerMsgChange() = let msg = "Very Important" printfn "%s" msg printfn "%s" msg innerMsgChange() printfn "%s" msg printMsg() 

I expected the text output to be in this sequence:

Important, very important, important, important

or

Important, very important, very important, important

but i got it

Important, important, very important, important

It seems that these functions do not correspond to the order of code execution. Why am I missing something?

+4
source share
2 answers

First of all, it is important to note that innerMsgChange does not do what its name promises: it creates a new variable called msg (which is not completely connected to an external variable, also called msg ) with the value "Very Important", and then prints it. Therefore, in essence, he prints the line "Very Important" and that it is.

So what is the code execution order? Plain:

  • msg variable set to Important
  • This variable is printed.
  • The innerMsgChange function innerMsgChange defined, but not called (this is not the step that is actually performed as such, so nothing happens on this line)
  • msg variable printed again
  • innerMsgChange() is called

    5.1. The msg internal variable is set to Very Important. Let me refer to it as innerMsg to disamigateate.

    5.2. innerMsg .

  • msg (which is still Important because it is completely unrelated to innerMsg ) is printed again.

+8
source

The conclusion will be as expected

1) Important -> printfn "% s" msg (line 3)

then you define the function, not call it.

2) Important -> printfn "% s" msg (line 7)

Now you name it.

3) Very important -> printfn "% s" msg (line 6 inside innerMsgChange function)

4) Important -> printfn "% s" msg (line 9)

+1
source

All Articles