Hi
I am new to crystal and trying small programming exercises to understand the language.
This exercise is about use tail recursion to implement Fibonacci series.

def fib(n, x = 1_i64, y = 1_i64)
n <= 1 ? y : fib(n - 1, y, x + y)
end
puts fib(46)

it works, but it can be called wrong, like so fib(42, 2, 4)

what i want to be able to do is something like

def fib(n)
def fib_impl(n, x = 1_i64, y = 1_i64)
n <= 1 ? y : fib_impl(n - 1, y, x + y)
end
fib_impl(n)
end
puts fib(46)

If you want to see how the call is emitted in llvm, a slightly modified version of the program that can be compiled without the std-lib prelude can be compiled without debug information and with either --emit=llvm-ir or DUMP=1

def fib(n, x = 1_i64, y = 1_i64)
n <= 1 ? y : fib(n &- 1, y, x &+ y)
end
fib(46)

I actually was curious about this exact question the other day! For a simple Fibonacci implementation like the first one I had above (I didn’t check for the second one), in --release mode LLVM does actually turn it into tail calls!