Hacker News new | ask | show | jobs
by junke 3461 days ago
Generic functions: functional yet dynamically dispatched.
1 comments

Generics aren't dynamically dispatched. Java has type erasure and C# emits variants for every instance.
No, I was talking about (Common) Lisp's generic functions (http://clhs.lisp.se/Body/m_defgen.htm). I realize I did not give enough context. Define a generic function:

    (defgeneric garnish (what with-what))
Specialize it on one or multiple arguments:

    (defmethod garnish ((c cocktail) (f fruit)) ...)
    (defmethod garnish ((s sandwich) (h ham)) ...)
    ...
But you can use it like a function:

    (let ((currified (rcurry #'garnish :curry)))
      (map 'list currified items))
Ah my bad! :)

These look very much like Clojure's protocols and multi-methods.

Yes, more like multi-methods, except for standard qualifiers (:around, :before, ...) and user-defined ones. OTOH, Clojure allows you to define a custom dispatch function.
Ah yes, Clojure has no first-class support for aspects. Its easy enough to monkey patch definitions for the rare case when its needed.

Most of the time however I try to avoid aspects as they introduce hidden behaviour in existing functions, which can be hard to reason about at scale, especially with more than a few developers.

I use them all the time. It's a great way to separate responsibilities.