相关疑难解决方法(0)

我应该如何避免在Ruby中导致错误的memoization?

关于如何避免由于可变状态导致错误的memoization,是否有共识?

在此示例中,缓存的结果的状态发生了突变,因此在第二次调用时得出了错误的结果.

class Greeter

  def initialize
    @greeting_cache = {}
  end

  def expensive_greeting_calculation(formality)
    case formality
      when :casual then "Hi"
      when :formal then "Hello"
    end
  end

  def greeting(formality)
    unless @greeting_cache.has_key?(formality)
      @greeting_cache[formality] = expensive_greeting_calculation(formality)
    end
    @greeting_cache[formality]
  end

end

def memoization_mutator
  greeter = Greeter.new
  first_person = "Bob"
  # Mildly contrived in this case,
  # but you could encounter this in more complex scenarios
  puts(greeter.greeting(:casual) << " " << first_person) # => Hi Bob
  second_person = "Sue"
  puts(greeter.greeting(:casual) << " " << second_person) # => …
Run Code Online (Sandbox Code Playgroud)

ruby state memoization

8
推荐指数
1
解决办法
462
查看次数

标签 统计

memoization ×1

ruby ×1

state ×1