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!
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In Ruby,
method_missingis 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.