[英]Platform-independent math functions in Clojure(script)
How to access things like sin
, cos
or PI
in a pure Clojure way?如何以纯粹的 Clojure 方式访问
sin
、 cos
或PI
类的东西?
For example, if I want to write a pure library, I mustn't use anything like (.PI Math)
(Java) or (.‑PI js/Math)
(JS).例如,如果我想写一个纯库,我不能使用像
(.PI Math)
(Java) 或(.‑PI js/Math)
(JS) 之类的东西。
The easiest way is to use Cljx: https://github.com/lynaghk/cljx最简单的方法是使用 Cljx: https : //github.com/lynaghk/cljx
With it you can write something like:有了它,您可以编写如下内容:
(* 5 #+clj (.PI Math) #+cljs (.‑PI js/Math))
and have this code compiled properly to Clojure and ClojureScript.并将此代码正确编译为 Clojure 和 ClojureScript。
As far as I know there's no better way to write one code to be runned as Clojure/ClojureScript.据我所知,没有更好的方法来编写一个作为 Clojure/ClojureScript 运行的代码。
There are some plans to include platform detection in Clojure itself but I think it's not ready yet.有一些计划在 Clojure 本身中包含平台检测,但我认为它还没有准备好。
Cljx has been deprecated for a few years. Cljx 已经被弃用了几年。 See the transition guide , which is also a good overview of the new solution:
请参阅转换指南,它也是新解决方案的一个很好的概述:
.cljc
Code targeting multiple Clojure platforms is written in .cljc
files using reader conditionals (introduced in Clojure 1.7 ).针对多个 Clojure 平台的代码使用阅读器条件(在 Clojure 1.7 中引入)编写在
.cljc
文件中。
The excellent kixi.stats implements platform-independent Clojure math using cljc, providing us not only a useful library but also a nice example of the approach.优秀的kixi.stats使用cljc实现了独立于平台的 Clojure 数学,不仅为我们提供了一个有用的库,而且还提供了一个很好的方法示例。 An excerpt:
摘录:
(def PI
#?(:clj Math/PI
:cljs js/Math.PI))
(defn sin [x]
#?(:clj (Math/sin x)
:cljs (js/Math.sin x)))
(def infinity
#?(:clj Double/POSITIVE_INFINITY
:cljs js/Infinity))
This code is from kixi.stats.math
.此代码来自
kixi.stats.math
。
Sin example:罪的例子:
(.sin js/Math 3)
PI example: PI示例:
(aget js/Math "PI")
Displaying in console:在控制台中显示:
(.log js/console (aget js/Math "PI"))
Hope that helps.希望有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.