How to access things like sin
, cos
or PI
in a pure Clojure way?
For example, if I want to write a pure library, I mustn’t use anything like (.PI Math)
(Java) or (.‑PI js/Math)
(JS).
How to access things like sin
, cos
or PI
in a pure Clojure way?
For example, if I want to write a pure library, I mustn’t use anything like (.PI Math)
(Java) or (.‑PI js/Math)
(JS).
The easiest way is to use 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.
As far as I know there’s no better way to write one code to be runned as Clojure/ClojureScript.
There are some plans to include platform detection in Clojure itself but I think it’s not ready yet.
clojure.math
& cljs.math
For simple constants or common mathematical functions, the first thing I'd reach for (other than interop) would be the clojure.math
and cljs.math
libs, which provide cljs.math/PI
, clojure.math/sin
, and so on.
Another answer suggests Cljx, which has been deprecated for a few years. 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).
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. 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
.
Sin example:
(.sin js/Math 3)
PI example:
(aget js/Math "PI")
Displaying in console:
(.log js/console (aget js/Math "PI"))
Hope that helps.
© 2022 - 2024 — McMap. All rights reserved.