Created
June 12, 2012 14:02
-
-
Save cassiano/2917713 to your computer and use it in GitHub Desktop.
Memoization example remembering the caller
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Original idea probably due to Robert Feldt | |
| module Memoize | |
| def remember(name) | |
| memory = {} | |
| original_method = instance_method(name) | |
| define_method(name) do |*args| | |
| memory[self] ||= {} | |
| if memory[self].has_key?(args) | |
| memory[self][args] | |
| else | |
| original = original_method.bind(self) | |
| memory[self][args] = original.call(*args) | |
| end | |
| end | |
| end | |
| end | |
| class Discounter | |
| extend Memoize | |
| def discount(*skus) | |
| expensive_discount_calculation(*skus) | |
| end | |
| remember :discount | |
| private | |
| def expensive_discount_calculation(*skus) | |
| puts "Expensive calculation for #{skus.inspect}" | |
| skus.inject {|m,n| m + n } | |
| end | |
| end | |
| d = Discounter.new | |
| puts d.discount(1,2,3) | |
| puts d.discount(1,2,3) | |
| puts d.discount(2,3,4) | |
| puts d.discount(2,3,4) | |
| e = Discounter.new | |
| puts e.discount(1,2,3) | |
| puts e.discount(1,2,3) | |
| puts e.discount(2,3,4) | |
| puts e.discount(2,3,4) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Expensive calculation for [1, 2, 3]
6
6
Expensive calculation for [2, 3, 4]
9
9
Expensive calculation for [1, 2, 3]
6
6
Expensive calculation for [2, 3, 4]
9
9