Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure Method Missing

Does anybody know how to implement method_missing (à la Ruby) in Clojure? E.g.

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

It would be very useful for a DSL, if used correctly.

Thanks in advance!

like image 479
alexanderpine Avatar asked Sep 03 '11 18:09

alexanderpine


1 Answers

In Ruby, method_missing is one of the primary constructs for metaprogramming. It's tightly bound to Ruby's object oriented structure, dynamically creating methods in a class from 'metaclasses'. This can be done because in Ruby classes are objects too.

Since Clojure is a functional language, mimicking this Rubyism makes little sense. However, one of the basic idioms of Lisps (such as Clojure), is that code is data: and as code can generate data, it can generate code also. The primary way to do this metaprogramming in Lisp is macros.

I'd suggest reading more about macros and their dos and don'ts. Be advised though that just like in Ruby, dynamically generated code is generally harder to debug and maintain. Often clever use of other functional idioms can be a better structural solution.

like image 104
NielsK Avatar answered Sep 28 '22 17:09

NielsK