4

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?

wmeyer
  • 3,426
  • 1
  • 18
  • 26
Miro
  • 1,778
  • 6
  • 24
  • 42
  • 2
    Your function doesn't execute until you call it. You have two variables named `msg`--one hides the other. – Daniel Sep 02 '11 at 20:10
  • You may find this question helpful to look at: http://stackoverflow.com/questions/2478079/f-shadowing-and-nested-function – Brian Sep 02 '11 at 20:43

2 Answers2

8

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:

  1. The variable msg is set to "Important"
  2. That variable is printed.
  3. The 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))
  4. The variable msg is printed again
  5. innerMsgChange() 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.

  6. msg (which still has the value "Important" because it's entirely unrelated to innerMsg) is printed again.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
1

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)

manojlds
  • 290,304
  • 63
  • 469
  • 417