Clojure元数据的一些用途是什么? [英] What are some uses of Clojure metadata?

查看:136
本文介绍了Clojure元数据的一些用途是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您在Clojure程序中如何使用元数据?

How have you used metadata in your Clojure program?

我看到了编程Clojure 的一个例子:

(defn shout [#^{:tag String} message] (.toUpperCase message))
;; Clojure casts message to String and then calls the method.

有什么用?这种形式的编程对我来说是全新的。

What are some uses? This form of programming is completely new to me.

推荐答案


  • Docstrings作为元数据存储在: doc键。

  • 返回和参数类型可以选择标记元数据,以避免在运行时在类型上反射的开销,从而提高性能。这些也称为类型提示。 #^ String 是一个类型提示。

  • 将内容保存在编译器下使用,如arglist函数,定义了var的行号,或者var是否包含对宏的引用。这些通常由编译器自动添加,通常不需要由用户直接操作。

  • 创建简单的测试用例作为函数定义的一部分:

    • Docstrings are stored as metadata under the :doc key. This is probably the number 1 most apparent use of metadata.
    • Return and parameter types can be optionally tagged with metadata to improve performance by avoiding the overhead of reflecting on the types at runtime. These are also known as "type hints." #^String is a type hint.
    • Storing things "under the hood" for use by the compiler, such as the arglist of a function, the line number where a var has been defined, or whether a var holds a reference to a macro. These are usually automatically added by the compiler and normally don't need to be manipulated directly by the user.
    • Creating simple testcases as part of a function definition:

      (defn#^ {:test(fn [](assert true))} something [] nil)

      (test#'something)

      如果你正在阅读Programming Clojure,那么第2章提供了一个很好的元数据介绍。图2.3提供了常见元数据的良好摘要。

      If you are reading Programming Clojure, then Chapter 2 provides a good intro to metadata. Figure 2.3 provides a good summary of common metadata.

      这篇关于Clojure元数据的一些用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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