Clojure Missing Method

Does anyone know how to implement method_missing (Γ  la Ruby) in Clojure? For example.

(defn method_missing [name & args] (foo name args)) 

This would be very useful for DSL if used correctly.

Thanks in advance!

+7
source share
2 answers

In Ruby, method_missing is one of the basic metaprogramming constructs. It is closely related to the object-oriented structure of Ruby, dynamically creating methods in a class from "metaclasses". This can be done because Ruby classes also have objects.

Since Clojure is a functional language, there is little point in imitating this rubism. However, one of the main Lisps idioms (like Clojure) is that code is data: and since code can generate data, it can also generate code. The main way to do this metaprogramming in Lisp is through macros.

I would suggest learning more about macros and their dos, etc. Be careful though, as with Ruby, dynamically generated code is usually harder to debug and maintain. Often, clever use of other functional idioms may be the best structural solution.

+10
source

You can create a macro that will wrap function calls in a try-catch block that will catch this exception.

eg. Something like

 (with-default-method [fxn args default] ...) 

will expand to

 (try (fxn args) (catch java.lang.IllegalArgumentException _) (finally default)) 

Above all, this is waving, because I don’t think it’s a good idea at all: it is an abuse of the exception system, and I think it will do unexpected things.

I am not a Ruby person, but it seems to me that this function is baked in this language; in java, and with the clojure extension, you have to try to enable this, and it will not.

+5
source

All Articles