"Stack Level Too Deep" with Ackerman Function in Ruby

I am using Ruby v1.9.1 to write a program with the Ackermann function for my class at the university. The code is as follows:

def ackermann(n,m)
  if n == 0 && m > 0
    return m+1
  elsif n > 0 && m == 0
    return ackermann(n-1,1)
  elsif n > 0 && m > 00
    return ackermann(n-1,ackermann(n,m-1))
  else
    puts "Wrong input, m and n must be higher than 0"
  end
end

puts ackermann(5,5)

This is a very recursive function. Therefore, I get the error "The stack level is too deep (SystemStackError)." Is there a way or workaround to fix this error?

+5
source share
3 answers

Remember recursive calls. Create a map {[int, hyperlong] => hyperlong} s to use the dynamic programming approach to complete the stack space.

Here is a C ++ example: http://pastebin.com/tVQ7yB31

: ack (3, 10) 3 .

+1

, , .

.

+2

- ( , 6- ) TCO (Tail ). Ruby 1.9:

RubyVM::InstructionSequence.compile_option = {
  :tailcall_optimization => true,
  :trace_instruction => false,
}

LtU, -:

http://lambda-the-ultimate.org/node/2673

0

All Articles