When I run the following bit of code, I get 5050 printed out from mySum. I've defined mySum, but never invoked it. How can it print at all? Maybe this is weird because my background is Haskell and I'm used to passing the IO monad around to get things to do stuff - how/when are things evaluated in F#?
type main = obj [] -> int
let mySum = [1..100] |> List.sum |> printfn "%i"
[<EntryPoint>]
let main argv =
0
I've defined mySum, but never invoked it.
mySum
is not a function, as it takes no parameters. A function has to have at least one argument; if nothing "useful" can be passed, that will usually be the unit
value ()
.
mySum
is a value; more specifically, you are binding the value of the expression [1..100] |> List.sum |> printfn "%i"
to the name mySum
. That value in turn is ()
, as printfn
only causes a side effect and returns unit
. The expression is evaluated immediately when the value is bound, and all that remains are the side effect and the actual value.
As a function, mySum
would look like this:
let mySum () = [1..100] |> List.sum |> printfn "%i"
And calling it would simply be
mySum ()
That would cause the value 5050
to be printed out, and the return value of ()
would be automatically ignored.
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