【问题标题】:Return behavior for recursion in RubyRuby 中递归的返回行为
【发布时间】:2016-09-10 01:41:12
【问题描述】:

我正在研究一种简单的递归方法来在 Ruby 中实现 Euclid 算法,但发现自己陷入了弄清楚如何在达到基本情况后返回所需值的问题。这是我必须要做的事情:

def euclid_alg(larger,smaller)
  if larger % smaller == 0 && smaller != 1
    return smaller
  else
    puts 'calling self'
    euclid_alg(smaller, (larger % smaller))
    puts 'executed section after call'
  end
  puts "made it here #{smaller} #{larger}"
  nil
end
puts euclid_alg(100,15)

还有输出:

calling self
calling self
executed section after call
made it here 10 15
executed section after call
made it here 15 100

请注意,“puts euclid_alg(100,15)”没有输出,我期望它返回 100 和 15、5 的最大公约数。

为了排除故障,我将第 3 行的 return smaller 替换为 puts smaller。新的输出是:

calling self
calling self
5
made it here 5 10
executed section after call
made it here 10 15
executed section after call
made it here 15 100

在控制台输出中添加“made it here 5 10”可以清楚地表明,return 语句正在中断函数调用,而不是“父调用”。

如何更好地进行递归?

【问题讨论】:

  • 读者:来自Wiki,欧几​​里得算法“是一种计算两个数的最大公约数(GCD)的有效方法,最大公约数将这两个数相除而不留下余数。 "

标签: ruby recursion


【解决方案1】:

您的代码很好。你只是错过了回报。注意:

def euclid_alg(larger,smaller)
  if larger % smaller == 0 && smaller != 1
    return smaller
  else
    puts 'calling self'
    return euclid_alg(smaller, (larger % smaller)) # <<<<<  Return here
    puts 'executed section after call'
  end
  puts "made it here #{smaller} #{larger}"
  nil
end
puts euclid_alg(100,15)

【讨论】:

    猜你喜欢
    • 2015-11-10
    • 2021-10-17
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多