Recursion using only original list

I’m playing around with elixir and solving some leetcode problems but I ran into an issue. The following code:

defmodule Solution do
  @spec climb_stairs(n :: integer) :: integer
  def climb_stairs(n) do
    climb_stairs(n, [1,0]) 
  end

  def climb_stairs(1, lis) do
    [first, second | _] = lis
    first + second
  end

  def climb_stairs(n, lis) do
    [first, second ] = lis
    climb_stairs(n-1, [first + second, second])
  end
end

always has lis be [1,0] (the result is always 1). Could someone explain what I’m doing wrong?

Hi @bendevski welcome! It would be helpful if you could explain what this function is supposed to do.

1 Like

You never actually change the list:

lis = [1, 0] # this is what you start with

# hitting the first clause of `climb_stairs/2` you do:
[1, 0 | _] = lis
1 + 0
# returns 1

# hitting the second clause of `climb_stairs/2` you do:
[1, 0] = lis
climb_stairs(…, [1 + 0, 0])
# calls `climb_stairs` again with `[1, 0]`
# eventually this reaches the first clause getting to the above case.
1 Like

Thank you for the clear explanation. Mixed up the variables in my head and thought it was a language thing.