使用Ruby注射计算嵌套总和



我正在尝试使用Ruby的注入来概括一个代表有限持续分数的数组,其中

[a, b, c, d, e, ... , x] = a + 1/(b + 1/(c + 1/(d + 1/(e + ... 1/x)...)))

我不知道如何获得适当的嵌套评估以使用注射返回正确的值。

相反,我所写的内容只是返回术语的平坦总和,而不是嵌套的总和。例如,

total = [0, 2, 1, 12, 8].inject do |sum,x|
  sum = sum + Rational(1,x)
end
puts total
#=>  41/24

也就是 0 + 1/2 + 1/1 + 1/12 + 1/8 #=> 41/24代替 0 + 1/(2 + 1/(1 + 1/(12+1/8))) #=> 105/307,这是正确的值。

是否可以使用注入方法计算此类总和?

如果没有,我该如何正确计算?

arr = [0, 2, 1, 12, 8]
arr.reverse.reduce { |tot, n| n + Rational(1, tot) }
  #=> 105/307

步骤:

a = arr.reverse
  #=> [8, 12, 1, 2, 0] 
b = a.reduce do |tot ,n|
  puts "tot=#{tot}, n=#{n}"
  (n + Rational(1, tot)).tap { |r| puts "  tot=#{r}" }
end
  #=> (105/307) 

此打印:

tot=8, n=12
  tot=97/8
tot=97/8, n=1
  tot=105/97
tot=105/97, n=2
  tot=307/105
tot=307/105, n=0
  tot=105/307

或者,可以使用递归。

def recurse(arr)
  arr.size == 1 ? arr.first : arr.first + Rational(1, recurse(arr.drop(1)))
end
recurse arr
  #=> (105/307)

最新更新