You can do this using multimethods. defmulti and defmethod will allow you to do everything you ask for apart from adding a doc-string to each command. Have a look at: http://clojuredocs.org/clojure_core/clojure.core/defmulti
On Thursday, May 29, 2014 3:05:56 AM UTC+2, Will Duquette wrote: > > If there's a better place to ask this kind of question, please point me in > the right direction! > > I'm learning Clojure, and part of the project I'm making is a command > language: the user can type commands at the application in something like a > REPL, and have a dialog with the application. I want to dispatch to a > function that carries out the command based on the first word of the > command; the function then receives the remaining words in the command, and > can do with them what it likes. So I'm going to need a map, something like > > { "dothis" #'commands/dothis, "dothat" #'commands/dothat ...} > > The question is, how best to build up that map? I'd like to define a > command like this: > > (command "dothis" > "Documentation string" > [argv] > ....) > > and have (command) define the function and add the entry to the map. > > I can think of all kinds of ways to do this. I could define > > (def command-map {}) > > and then have (command) rebind it: > > ... > (def command-map (assoc command-map name function)) > > but I know that's frowned upon. I could make command-map contain an atom, > and use (swap!) to update the atom, but really, the mapping isn't going to > change at run-time. I could make (command) a macro, so that it's really > updating command-map at the top-level, but that seems cheesy. > > Or, I could make (command) define the function as a public function in the > 'commands namespace, which would be reserved for that purpose, and attach > the command name, e.g., "dothis" to the function as metadata. Then I could > build the map by querying the namespace using (ns-publics). > > Is there is a normal way to do this kind of thing? > -- You received this message because you are subscribed to the Google Groups "Clojure" group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en --- You received this message because you are subscribed to the Google Groups "Clojure" group. To unsubscribe from this group and stop receiving emails from it, send an email to clojure+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.