Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my application executing top to bottom

Tags:

f#

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?

like image 717
Anthony Russell Avatar asked Feb 24 '17 03:02

Anthony Russell


1 Answers

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
like image 177
MarcinJuraszek Avatar answered Nov 05 '22 18:11

MarcinJuraszek