Hacker News new | ask | show | jobs
by betterunix2 2665 days ago
In this context I think it refers to mathematical objects, since the dependencies can be between either values or types in either direction (values to values, types to types, types to values, values to types).

Also, lexical closures in a functional language are "classes" from the OO setting, so it is natural to implement classes if you want them; see e.g. OCaml. What you rarely see in the functional setting are common OO design patterns, because many of those patterns are unnecessary or awkward in functional languages.

5 comments

I don't think you meant to imply this, but for anyone else - please note that the reverse can also be said - closures from an FP setting are objects from an OO setting, and it is natural to implement closures if you want them; see e.g. C++ "functors".

That is, objects and closures can both be implemented in terms of the other, if your language doesn't happen to offer both.

Lots of discussion and links on this at http://wiki.c2.com/?ClosuresAndObjectsAreEquivalent
I think Scala does a good job of unifying OO and FP. And because of everything being first class, you get to eliminate all the ridiculeous design patterns and end up with a very nice FP system based upon objects and traits or typeclasses
Thank you, I never knew how ignorant I was about that.
Could you explain what you mean by closures being classes? My only familiarity is from Emacs/Common Lisp and Clojure.
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.