0

How can I write the following function in a more efficient manner to reduce the number of recursive calls made?

declare
fun {Calc N}
    if N == 0 then 2
    elseif N == 1 then 4
    elseif N == 2 then 8
    else {Calc N-1}+{Calc N-2}+{Calc N-3}
    end
end

1 Answers1

1

I think this is what you are looking for :

declare
fun {Calc N}
   fun {CalcAux N A B C}
      if N==0 then A
      else {CalcAux N-1 B C A+B+C}
      end
   end
in
   {CalcAux N 2 4 8}
end

The three recursive calls are in a single statement in your version, it increases the number of calls to the function but also the execution stack size each time the statement is computed. The use of three accumulators (A, B and C) allows us to make at most one recursive call each time we enter the CalcAux function.

demesmaekerf
  • 146
  • 1
  • 6