Created
June 13, 2012 12:14
-
-
Save cassiano/2923694 to your computer and use it in GitHub Desktop.
Memoization with and without context
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, options = {}) | |
| memory = {} | |
| original_method = instance_method(name) | |
| define_method(name) do |*args| | |
| lookup = options[:context] ? (memory[self] ||= {}) : memory | |
| if lookup.has_key?(args) | |
| lookup[args] | |
| else | |
| original = original_method.bind(self) | |
| lookup[args] = original.call(*args) | |
| end | |
| end | |
| end | |
| end | |
| class Discounter | |
| extend Memoize | |
| def discount(*skus) | |
| expensive_discount_calculation(*skus) | |
| end | |
| alias_method :discount2, :discount | |
| remember :discount | |
| remember :discount2, :context => true | |
| private | |
| def expensive_discount_calculation(*skus) | |
| puts "Expensive calculation for #{skus.inspect}" | |
| skus.inject {|m,n| m + n } | |
| end | |
| end | |
| puts '------- discount ---------' | |
| puts 'Using d:' | |
| 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) | |
| puts 'Now using e:' | |
| 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) | |
| puts '------- discount2 ---------' | |
| puts 'Using d:' | |
| d = Discounter.new | |
| puts d.discount2(1,2,3) | |
| puts d.discount2(1,2,3) | |
| puts d.discount2(2,3,4) | |
| puts d.discount2(2,3,4) | |
| puts 'Now using e:' | |
| e = Discounter.new | |
| puts e.discount2(1,2,3) | |
| puts e.discount2(1,2,3) | |
| puts e.discount2(2,3,4) | |
| puts e.discount2(2,3,4) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
------- discount ---------
Using d:
Expensive calculation for [1, 2, 3]
6
6
Expensive calculation for [2, 3, 4]
9
9
Now using e:
6
6
9
9
------- discount2 ---------
Using d:
Expensive calculation for [1, 2, 3]
6
6
Expensive calculation for [2, 3, 4]
9
9
Now using e:
Expensive calculation for [1, 2, 3]
6
6
Expensive calculation for [2, 3, 4]
9
9