Hacker News new | ask | show | jobs
by Jim_Heckler 2668 days ago
Could you explain what you mean by closures being classes? My only familiarity is from Emacs/Common Lisp and Clojure.
2 comments

Define a set of functions that close over their lexical environment, then treat the closed-over variables as internal/private state, and treat those functions as you would methods in OOP (reading/mutating the aforementioned variables).
That's basically the same level of OOP compared to how one can implement numbers and numeric operations as functions.
Classes are a combination of member variables, methods, and method dispatch (which is important for inheritance). So let's emulate that combination with a closure in Lisp:

  (defun constructor (x y)
    (list (lambda (a) (+ x a)) (lambda (a) (* y a))))
This is essentially a "v-table" as you would have in C++. Inheritance would be exactly what you expect: replacing v-table methods in child class constructors. Lisp is untyped but if you wanted to do this in a typed language then a class type would just be the types of the methods that can be applied and what index in the v-table each method type has, similar to duck typing (except that the methods are "named" by v-table index). Note that members are private, and can only be accessed if the interface (v-table type) allows it, and that in a pure implementation you would have immutable objects so "setters" would have to recursively call the constructor.