Created
July 18, 2012 03:28
-
-
Save sgonyea/3133987 to your computer and use it in GitHub Desktop.
Infinite Cache: Python vs. Ruby
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
# In Python: | |
from collections import defaultdict | |
def infinite_cache(): | |
cache = lambda: defaultdict(cache) | |
return cache() | |
cache = infinite_cache() |
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
# In Ruby: | |
cache = Hash.new do |h,k| | |
h[k] = Hash.new(&h.default_proc) | |
end | |
# Or, if you want to mimic the Python version: | |
def infinite_cache | |
block = lambda {|h,k| h[k] = Hash.new(&block) } | |
Hash.new(&block) | |
end | |
cache = infinite_cache | |
# Mimic it even further, as Ruby's Hash doesn't have quite the same behavior as Python's "defaultdict" wrapper: | |
class DefaultHash < Hash | |
def initialize(value=nil, &block) | |
value ||= block | |
case value | |
when Proc, Method then self.default_proc = proc {|h,k| h[k] = value.call } | |
when Class then self.default_proc = proc {|h,k| h[k] = value.new } | |
else | |
self.default = value | |
end | |
end | |
end | |
def infinite_cache | |
cache = proc{ DefaultHash.new(cache) } | |
cache[] | |
end | |
cache = infinite_cache |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment