Hacker News new | past | comments | ask | show | jobs | submit login

> 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



In fact, in SICP, they build their object system in this way, if my memory serves me correctly.


Of course. Closures are, after all, a poor man's objects[1].

[1] http://codermonk.blogspot.com/2007/01/venerable-master-qc-na...




Consider applying for YC's W25 batch! Applications are open till Nov 12.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: