3

如何从平方数的开头制作序列,然后将其添加到上一个结果中?

7 => 49, 56, 63, ...

def make_sequence(number)
  lambda { number*number ??? }
end

num = make_sequence(7)
num.call #=> 49
num.call #=> 56
...
4

3 回答 3

3

按照你最初的想法使用闭包我会写:

def make_sequence(n)
  x = n**2 - n
  lambda { x += n }
end

num = make_sequence(7)
p num.call #=> 49
p num.call #=> 56
于 2012-10-31T10:10:18.247 回答
2

使用枚举器

def make_sequence(start)
  pos = start**2
  Enumerator.new do |y|
    loop do
      y.yield(pos)
      pos += start
    end
  end
end

seq = make_sequence(7)
seq.next   #=> 49
seq.next   #=> 56

...
于 2012-10-31T10:05:15.907 回答
2

光纤版本:

def make_sequence(num)
  inc = num
  num = num*num
  Fiber.new do
    loop do
      Fiber.yield(num)
      num += inc
    end
  end
end

a = make_sequence(7)
p a.resume  #=> 49
p a.resume  #=> 56
p a.resume  #=> 63
...
于 2012-10-31T10:08:52.337 回答