I have noticed that when I call a function multiple times with the same arguments, all of them immutable, in the same scope, the compiler does not save the result of the first call to be used as the result of the other calls. The function neither change nor depend on any outside state. The context is completely “pure and immutable”, at least as much as F# is, I’m aware that it allows impurity and almost everything that can be done with .Net. I created this simple code example to demonstrate what I mean:
let rec pureFib n : int64 =
if n = 0 then
1L
elif n = 1 then
1L
else pureFib(n - 2) + pureFib(n - 1)
let shouldBeCalledOnce n =
let r1 = pureFib n
let r2 = pureFib n
r1 + r2
On my computer calling shouldBeCalledOnce with n > 42 last enough to notice the difference, you can also use this entry point to test it in a console application.
[<EntryPoint>]
let main argv =
let crono = System.Diagnostics.Stopwatch.StartNew()
let v = shouldBeCalledOnce 43
printfn "%A" crono.ElapsedMilliseconds
int v
The issue (if there is really one) is easy to get, so, I suppose there is no need for complex benchmarks. I compiled the code with optimize+ and without debug information, only pdb.
If one of the key features of functional programming is that a function will always return the same value when called with the same arguments, that’s something the compiler should use to avoid multiple meaningless calls to save time, and in some cases improve readability and the understanding of code.
In short, my questions are the following:
1. Does F# compiler have a way of optimizing multiple calls to pure functions?
2. For that first question to be true, it would imply that the compiler was able to know when a function is pure and when it is not. Does it?