I thought I understood F# code execution but clearly I'm missing something. When I run the following
#!/usr/bin/env fsharpi
let a =
System.Console.WriteLine("Function A")
let b =
System.Console.WriteLine("Function B")
let c =
System.Console.WriteLine("Function C")
c
b
a
I get the output:
Function A
Function B
Function C
So for some reason it's executing the functions as it reads them in instead of the function calls which are in reverse order.
Why is this?
I think you're misunderstanding what this line means:
let a =
System.Console.WriteLine("Function A")
It assigns the result of System.Console.WriteLine("Function A")
to a
. If you run it you'll see a
is typed as unit
:
val a : unit = ()
And at that time "Function A" was already written to console.
What you probably want is a
to be a function and not a value:
let a() =
System.Console.WriteLine("Function A")
It can be called using a()
. If you put that all together:
let a() =
System.Console.WriteLine("Function A")
let b() =
System.Console.WriteLine("Function B")
let c() =
System.Console.WriteLine("Function C")
c()
b()
a()
you'll get what you expect:
Function C
Function B
Function A
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