I’m an F# beginner. 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 that text output would be in this sequence:
Important, Very Important, Important, Important
or this
Important, Very Important, Very Important, Important
but I got this
Important, Important, Very Important, Important
it seems that these functions don’t comply with code execution order. Why is that, am I missing something?
First of all its important to point out that
innerMsgChangedoes not do what its name promises: It creates a new variable calledmsg(which is entirely unrelated to the outer variable which is also calledmsg) with the value “Very Important” and then prints it. So in essence it prints the string “Very Important” and that’s it.So which order is the code executed in? Simple:
msgis set to “Important”innerMsgChangefunction is defined, but not called (that isn’t a step that’s actually executed as such, so basically nothing happens on this line(s))msgis printed againinnerMsgChange()is called5.1. The inner variable
msgis set to “Very Important”. Let’s refer to it asinnerMsgto disamiguate.5.2.
innerMsgis printed.msg(which still has the value “Important” because it’s entirely unrelated toinnerMsg) is printed again.