Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# confusing output

Tags:

f#

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?

like image 715
Miro Avatar asked Jan 18 '23 19:01

Miro


2 Answers

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.

like image 133
sepp2k Avatar answered Jan 24 '23 17:01

sepp2k


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)

like image 27
manojlds Avatar answered Jan 24 '23 17:01

manojlds