<div dir="ltr">Hello <div><br></div><div>I was trying to work through finding fibonacci number 10 days ago and my first attempt looked like  </div><div><br></div><div><div>-module(solution).</div><div>-export([main/0, fib/2]).</div><div><br></div><div><br></div><div>main() -></div><div>  {ok, [N]} = io:fread("", "~d"),</div><div>  io:format("~p~n", [fib(N, maps:new())]).</div><div><br></div><div>fib(1, _) -> 0;</div><div>fib(2, _) -> 1;</div><div>fib(N, Map) -></div><div>  case maps:find(N, Map) of</div><div>    {ok, Value} -> Value;</div><div>    error -> fib(N -1, Map) + fib(N-2, Map)</div><div>  end.</div></div><div><br></div><div>Then I realized that tho is going to be very inefficient to store all values. Plus for large numbers the recursion will create lot more stacks. no no!</div><div><br></div><div>This morning I spent some time to learn the concept of Tail Recursion and re-tried the same problem again with following code</div><div><br></div><div><div>-module(solution).</div><div>-export([main/0]).</div><div><br></div><div>main() -></div><div>  {ok, [N]} = io:fread("", "~d"),</div><div>  io:format("~p~n", [fib(N, 0, 1)]).</div><div><br></div><div>fib(1, Prev, _) -> Prev;</div><div>fib(N, Prev, Next) when N > 0 -></div><div>  fib(N-1, Next, Prev + Next).</div></div><div><br></div><div>I wanted to check through the community to learn about better ways to solve the problem.  </div><div><br></div><div><b>Question</b></div><div><ol><li>Since the concept for tail recursion is new to me I specially wanted to ask that how could I model my thinking to turn recursive functions into tail-recursive functions? </li><li>Can we turn every recursive function into tail-recursive? If no, how to identify?</li><li>Any other valuable recommendation based on your learnings?</li></ol><div>Thank you</div></div><div>+ Harit Himanshu</div></div>