Trans
8/30/2007 12:02:00 AM
On Aug 29, 4:40 pm, "Keith Rarick" <k...@essembly.com> wrote:
> On 8/29/07, Daniel DeLorme <dan...@dan42.com> wrote:
>
> > what about:
> > class C
> > decorate :memoized do
> > def ...
> > end
> > end
>
> > That makes the implementation much more simple and solid than relying on
> > method_added which may be incorrectly overridden somewhere.
>
> I like that. I think the gain in robustness more than offsets the
> slight degradation (IMO) in readability. What would it look like for
> class methods? Something like this? I don't know how I would implement
> example 2 below.
>
> class C
>
> # Example 1 (instance method)
> decorate :memoized do
> def tak(x, y, z)
> return z if x <= y
> tak(tak(x - 1, y, z), tak(y - 1, z, x), tak(z - 1, x, y))
> end
> end
>
> # Example 2 (class method)
> decorate :memoized do
> def self.tbk(x, y, z)
> return z if x <= y
> tbk(tbk(x - 1, y, z), tbk(y - 1, z, x), tbk(z - 1, x, y))
> end
> end
>
> # Example 3 (class method)
> class << self
> decorate :memoized do
> def tck(x, y, z)
> return z if x <= y
> tck(tck(x - 1, y, z), tck(y - 1, z, x), tck(z - 1, x, y))
> end
> end
> end
>
> end
Just a thought...
There's this trick I always want to use to define class-level module
methods that would be "inherited" through the class hierarchy.
Unfortunately it's doesn't work because the method still winds up in a
class rather than a module. However, it can be used for other things.
And this might be a good case. Using your examples:
# Example 1 (instance method)
def memoized.tak(x, y, z)
return z if x <= y
tak(tak(x - 1, y, z), tak(y - 1, z, x), tak(z - 1, x, y))
end
# Example 3 (class method)
class << self
def memoized.tck(x, y, z)
return z if x <= y
tck(tck(x - 1, y, z), tck(y - 1, z, x), tck(z - 1, x, y))
end
end
Interestingly, the only place I've used this trick so far is for
#meta, which allows me to define class methods by-passing access
privacy. For instance I can use it to do:
class X
meta.attr_writer :foo
end
instead of
class X
class << self
attr_writer :foo
end
end
It should even be possible to combine this with example #3 to do:
# Example 3 (class method)
def meta.memoized.tck(x, y, z)
return z if x <= y
tck(tck(x - 1, y, z), tck(y - 1, z, x), tck(z - 1, x, y))
end
T.