如何在clojure中设置和获取多方法元数据? [英] How to set and get multimethod metadata in clojure?

查看:150
本文介绍了如何在clojure中设置和获取多方法元数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用multimethods来解析命令行命令及其参数。

I'm using multimethods to parse command line commands and their arguments.

(defmulti run (fn [command args] command))

(defmethod run :default
  [& _]
  ...)

^{:args "[command]"}
(defmethod run "help"
  [_ & [args]]
  "Display command list or help for a given command"
  ...)

^{:args ""}
(defmethod run "version"
  [_ & [args]]
  "Print program's version"
  ...)

(defn -main
  [& args]
  (run (first args)
    (next args)))

当我尝试访问元数据时,对于特定方法,clojure返回 nil

When I try to access the metadata, for a specific method, clojure returns nil:

(meta ((methods run) "help"))


推荐答案

没有这样的可能性。第一个原因(简单的一个)是 defmethod 不提供为特定方法设置元数据的能力(只有 defmulti 允许,但只对整个多重方法)。第二个原因是多方法本质上是一个单一的函数,只有多个执行的变体,每个都根据传递的参数触发。 Rougly说,从调用者的角度来看,函数 f1 f2 之间没有特殊的区别:

There's no such possibility. The first reason (straightforward one) is that defmethod doesn't provide an ability to set metadata for a particular method (only defmulti allows that, but only for the whole multimethod). Second reason is that multimethod is essentially a single function, just with multiple "variants" of execution, each of which fires depending on passed parameters. Rougly speaking, from caller point of view, there's no particular difference between functions f1 and f2 defined below:

(defmulti f1 (fn [x] x))

(defmethod f1 :foo [x]
  ...)

(defmethod f1 :bar [x]
  ...)

(defmethod f1 :baz [x]
  ...)

(defn f2 [x]
  (case x
    :foo ...
    :bar ...
    :baz ...))

我个人认为,取决于特定函数是多平面还是普通函数依赖于实现细节。另外,如果你需要显式地记录multimehod的每个方法,你应该考虑用普通函数替换每个方法,而不使用multimethods。

Personally, I'd consider depending on whether particular function is multimethod or ordinary function as relying on implementation details. Also if you need to explicitly document each method of multimehod, you should consider replacing each method with ordinary function and don't use multimethods at all.

这篇关于如何在clojure中设置和获取多方法元数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆