5 ms·
> Instances and closures are closely related: an instance is a piece of state with several operations that can be invoked on it, while a closure is a piece of s
by derefr 16y ago
> Instances and closures are closely related: an instance is a piece of state with several operations that can be invoked on it, while a closure is a piece of state with one operation that can be invoked on it.
I would go further, and say that they're equivalent—that "one operation" can be a dispatch function:
def make_object
x = 5
lambda do |m|
case m
when 'increment'
x += 1
when 'decrement'
x -= 1
when 'get'
x
end
end
end
o = make_object
o.call('get') # => 5
o.call('increment') # => 6
o.call('decrement') # => 5
- dkersten 16y agoIn fact, in SICP, they build their object system in this way, if my memory serves me correctly.
- khafra 16y agoOf course. Closures are, after all, a poor man's objects[1]. [1] http://codermonk.blogspot.com/2007/01/venerable-master-qc-na-was-walking-with.html http://codermonk.blogspot.com/2007/01/venerable-master-qc-na...