Hello,
On my project I have a process that has to run every 1 sec, fetching events and doing some work with them.
Should I use. a while true loop or recursive function? How does it affect memory usage?
Thanks
Hello,
On my project I have a process that has to run every 1 sec, fetching events and doing some work with them.
Should I use. a while true loop or recursive function? How does it affect memory usage?
Thanks
A tail recursive function doesn’t affect memory usage and is no different in that sense from a while/for or any other loop. A tail recursive function is such function that calls itself in the tail position. In general it means that the recursive call is not followed by any other operation, that uses the result of the call. For example, this is a tail recursive function
open Printf
let rec loop rounds =
if rounds > 0
then begin
printf "Rounds left %d\n" rounds;
loop (rounds - 1)
end
else printf "We are done!\n"
In this function, the loop (rounds - 1)
call is in the tail position and is not followed by any other expression.
Any loop could be rewritten using tail-recursion, so if you’re having a choice between using a while/for loop and a recursive function, then, given that recursion is a more natural representation of iteration, it is better to use the recursive function, instead of relying on adhoc for or while loops.
Nothe that you also can add the @tailcall annotation to ensure that the function will be properly tranformed in a loop. This code trigger a warning at the compilation
open Printf
let rec loop rounds =
if rounds > 0
then begin
printf "Rounds left %d\n" rounds;
try (loop [@tailcall]) (rounds - 1)
with Not_found -> printf "Error\n"
end
else printf "We are done!\n"
ocamlc test.ml
File "test.ml", line 7, characters 10-41:
Warning 51: expected tailcall