Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does printfn print immediately in f#?

Tags:

f#

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
like image 994
Carbon Avatar asked Dec 10 '22 16:12

Carbon


1 Answers

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.

like image 88
TeaDrivenDev Avatar answered Dec 19 '22 00:12

TeaDrivenDev