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 innerMsgChange
does not do what its name promises: It creates a new variable called msg
(which is entirely unrelated to the outer variable which is also called msg
) 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:
msg
is set to "Important"innerMsgChange
function is defined, but not called (that isn't a step that's actually executed as such, so basically nothing happens on this line(s))msg
is printed againinnerMsgChange()
is called
5.1. The inner variable msg
is set to "Very Important". Let's refer to it as innerMsg
to disamiguate.
5.2. innerMsg
is printed.
msg
(which still has the value "Important" because it's entirely unrelated to innerMsg
) is printed again.
The output is 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 call it.
3) Very Important -> printfn "%s" msg (line 6 inside function innerMsgChange)
4) Important -> printfn "%s" msg ( line 9)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With