gpt4 book ai didi

Clojure 编译时常量

转载 作者:行者123 更新时间:2023-12-04 09:55:44 25 4
gpt4 key购买 nike

这个问题纯属“心理主宰”,大概没有什么实用值(value)。

如果我使用 def 在 Clojure 中定义一个值,是否可以诱导编译器在编译时对其进行评估,而不是等到运行时?

(def the-answer 42)

(+ the-answer 1)

我想我可以定义一个宏,但调用语法变得有点尴尬:
(defmacro the-answer [] 42)

(+ (the-answer) 1)

这也有效,但仍然很难看:
(+ `~the-answer 1)

我也理解(或相信)Clojure 在编译时计算常量表达式:
(def milliseconds-per-day (* 24 60 60 1000))

我只是在学习 Common Lisp,但我的理解是 Common Lisp 支持用户定义的读取器宏,因此您可以定义一个读取器宏(类似于 #$ )在编译时评估以下符号:
(+ #$the-answer 1)

顺便说一句,该语法并不比宏调用“更漂亮”。

如何让 Clojure 在编译时评估常量 vars 并将引用替换为实际值?它已经这样做了吗?

在任何人开始引用 Knuth 定律(“过早优化是万恶之源”)之前,我提出这个问题是为了更好地理解 Clojure 编译的内部原理。

最佳答案

来自 Clojure 1.3 docs

== 2.14 ^:const defs ==

^:const lets you name primitive values with speedier reference.

(def constants {:pi 3.14 :e 2.71})

(def ^:const pi (:pi constants)) (def ^:const e (:e constants))

The overhead of looking up :e and :pi in the map happens at compile time, as (:pi constants) and (:e constants) are evaluated when their parent def forms are evaluated.

关于Clojure 编译时常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8079630/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com