Understanding Recursion

Hi, I am learning recursion these days and I wanted to implement a program that will print the values in Descending order (10, 9, 8, 7, 6, 5, …). As you can see in the following code. It should print out the positive values in descending order but it prints in ascending order.

Any Idea?

defmodule Recursion do

  def count(0), do: :ok

  def count(n) when n >= 0 do
    count(n-1)
    IO.puts(n)
  end

  def count(n) when n <=0 do
    :negative
  end
end

This is because you call the recursive call for the next number before printing the current number:

    count(n-1)
    IO.puts(n)

If you inverse the order, you will have the expected output, and also you will have a tail recursive function.

Edit: this is what happens when you call count(4):

call count(3)
  call count(2)
    call count(1)
      call count(0)
      call IO.puts(1)
    call IO.puts(2)
  call IO.puts(3)
call IO.puts(4)

8 Likes

Thats a solid answer … thanks alot, now i understood the concept.

2 Likes