Clojure 元数据有哪些用途? [英] What are some uses of Clojure metadata?

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

问题描述

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

How have you used metadata in your Clojure program?

我在Clojure 编程中看到了一个示例:

I saw one example from Programming 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.

推荐答案

  • 文档字符串作为元数据存储在 :doc 键下.这可能是第 1 种最明显的元数据用途.
  • 可以选择用元数据标记返回和参数类型,以避免在运行时反射类型的开销,从而提高性能.这些也称为类型提示".#^String 是一个类型提示.
  • 在幕后"存储供编译器使用的东西,例如函数的参数列表、定义 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)

      如果您正在阅读编程 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天全站免登陆