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.
Official wrapper APIs: 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.
Cljx
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.
Related
I'm quite new to functional programming and clojure. I like it.
I'd like to know what the community thinks about following fn-naming approach:
Is it a feasible way to go with such naming, or is it for some reason something to avoid?
Example:
(defn coll<spec>?
"Checks wether the given thing is a collection of elements of ::spec-type"
[spec-type thing]
(and (coll? thing)
(every? #(spec/valid? spec-type %)
thing)))
(defn coll<spec>?nil
"Checks if the given thing is a collection of elements of ::spec-type or nil"
[spec-type thing]
(or (nil? thing)
(coll<spec>? spec-type thing)))
now ... somewhere else I'm using partial applications in clojure defrecrod/specs ...
similar to this:
; somewhere inside a defrecord
^{:spec (partial p?/coll<spec>?nil ::widgets)} widgets component-widgets
now, I created this for colls, sets, hash-maps with a generic-like form for specs (internal application of spec/valid? ...) and with a direct appication of predicates and respectively a <p> instead of the <spec>
currently I'm discussing with my colleagues wether this is a decent and meaningful and useful approach - since it is at least valid to name function like this in clojure - or wether the community thinks this is rather a no-go.
I'd very much like your educated opinions on that.
It's a weird naming convention, but a lot of projects use weird naming conventions because their authors believe they help. I imagine if I read your codebase, variable naming conventions would probably not be the thing that surprises me most. This is not an insult: every project has some stuff that surprises me.
But I don't see why you need these specific functions at all. As Sean Corfield says in a comment, there are good spec combinator functions to build fancier specs out of simpler ones. Instead of writing coll<spec>?, you could just combine s/valid? with s/coll-of:
(s/valid? (s/coll-of spec-type) thing)
Likewise you can use s/or and nil? to come up with coll<spec>?nil.
(s/valid? (s/or nil? (s/coll-of spec-type) thing))
This is obviously more to write at each call site than a mere coll<spec>?nil, so you may dismiss my advice. But the point is you can extract functions for defining these specs, and use those specs.
(defn nil-or-coll-of [spec]
(s/or nil? (s/coll-of spec)))
(s/valid? (nil-or-coll-of spec-type) thing)
Importantly, this means you could pass the result of nil-or-coll-of to some other function that expects a spec, perhaps to build a larger spec out of it, or to try to conform it. You can't do that if all your functions have s/valid? baked into them.
Think in terms of composing general functions, not defining a new function from scratch for each thing you want to do.
Context
Our team is using some more functional patterns in other languages (IE javascript and ruby) and we've had some recreational conversations on standardized naming. My familiarity is largely limited to Clojure and Ramda.js.
Both Clojure and Ramda have assoc and Clojure has assoc-in with a Ramda version at assocPath. I'm guessing Ramda cribbed its name from Clojure here.
I note that common lisp doesn't seem to even have a clear comparable to assoc-in. See this conversation.
The Question
What other lisps or lisp-likes have assoc and assoc-in comparables, and what do they call them?
Bonus Points
Do there exist any resources for "rosetta stone" inter-lisp comparison of function names? A place to easily see where comparable behavior has similar or different names, or to see where comparable names have similar or different behavior?
You're right that Common Lisp doesn't have assoc-in or something similar. I would say, overall, it has pretty basic support for hash-table operations in the standard library (which I attribute to lack of practical experience with them at the time of the development of the standard). However, even if more hash-table-related stuff was present, I still doubt something like assoc-in would be added. That's because, in Lisp, the preferred approach to deal with assignment is via the setf'able places machinery that involves the macro define-setf-expander.
For instance, the rutils library I am maintaining provides a lot of additional hash-table-related operators, as well as Clojure-like literal syntax for them. Yet, this is how I'd handle the assoc-in case using its primitives (including the ? operator that is a shorthand for generic-elt):
CL-USER> (ql:quickload :rutils)
CL-USER> (in-package :rtl-user)
RTL-USER> (named-readtables:in-readtable rutils-readtable)
RTL-USER> (toggle-print-hash-table)
RTL-USER> (let ((ht #{:a 1 :b 3}))
(setf (? ht :c) #{:d 33})
ht)
#{
:A 1
:B 3
:C #{
:D 33
}
}
I'd say that it's a question of taste which approach to prefer. To me, the Lisp one has more advantages: it's more uniform and explicit.
The other advantage is that the get-in part becomes really straightforward:
RTL-USER> (? * :c :d)
33
(Here, I use * to refer to the results of the previous REPL computation that happen to be the hash-table we created in the assoc-in exercise).
P.S. As for the Rosetta stones, here are a few attempts:
https://hyperpolyglot.org/lisp
https://lispunion.org/rosetta/
I'm starting to use clojure to test a java library. So my question is more "what is the clojure way of doing this".
I have a lot of code that looks like the following
...
(with-open [fs (create-filesystem)]
(let [root (.getFile fs path)]
(is (.isDirectory root))
(is (.isComplete root)))
(let [suc (.getFile fs (str path "/_SUCCESS"))]
(is (.isFile suc))
(is (.isComplete suc))))
Since this is a java object, I need to verify a set of properties are true on the object. I know about doto that will let me do things like
(doto (.getFile fs path)
(.setPath path2)
(.setName name2))
and --> will let me have a list of partial functions and have each result pass through each function. Been thinking that something like --> but keeps passing the same object like doto would help with these tests. Would something like this be a good way to do this, or am I not really doing this the clojure way?
Thanks for your time!
You can use doto:
(doto (.getFile fs path) (.setPath path2) (.setPath name2))
You may learn about other threading macros like cond->, as->, some-> etc... for "the Clojure way" purpose.
There's no macro that does exactly what you wanted. Only .. and doto are object-specific macros.
Because your question is more "the Clojure way" thing, I recommend this:
https://github.com/bbatsov/clojure-style-guide
Yes, you can use the .. macro for java interop with threading semantics.
Example:
(.. (SomeObject/newBuilder)
(withId 1)
(withFooEnabled true)
(build))
There is nothing wrong with using a let as you have; it is a very direct and clear implementation of what you want to do. I think it is the best approach :)
But it is interesting to examine how you could achieve this with Clojure built in macros too:
(doto (.getFile fs path)
(-> (.isDirectory) (is))
(-> (.isComplete) (is)))
doto is special in that it propagates the initial value. It takes subsequent forms and inserts the initial value into the second position of the forms.
-> allows you to arrange forms inside out... which means you can combine it with doto such that the initial value is threaded through whatever layers of forms you would like to execute on it.
Now doto and -> are macros, so the syntax can be a little confusing... if you prefer to use functions then juxt is handy for calling multiple functions:
((juxt #(is (.isDirectory %)) #(is (.isComplete))) (.getFile fs path))
But for this situation it's quite ugly :)
Coming back to your original question, you can of course also create your own syntax with a macro... I describe one approach here: http://timothypratley.blogspot.pt/2016/05/composing-test-assertions-in-pipeline.html which chains multiple assertions in a convenient way.
I think for the example you describe sticking with a let form is the best way as it is most obvious... the other forms are shown here to discuss the options available, some of which might be appropriate in other circumstances.
Being new to clojure I struggle with finding an idiomatic style for different code constructs.
In some cases my let bindings contain most of the code of a function. Is this bloat, some misunderstanding of clojure philosophy or idiomatic and just fine?
Here is a sample testcase to demonstrate. It tests an add/get roundtrip to some storage repository. Does the long let look wierd?
(deftest garden-repo-add-get
(testing "Test garden repo add/get"
(let [repo (garden/get-garden-repo)
initial-garden-count (count (.list-gardens repo))
new-garden (garden/create-garden "Keukenhof")
new-garden-id (.add-garden repo new-garden)
fetched-garden (.get-garden repo new-garden-id)]
(is (= (+ initial-garden-count 1) (count (.list-gardens repo))))
(is (= (.name new-garden) (.name fetched-garden))))))
Main problem I see with your let code, and is the usual case, is you're using lots of intermediate variables whom only have names in order to exist in the let form.
The best approach to avoid the overbloat is to use the arrow macro -> or ->>
For instance you can avoid repo intermediate variable with
initial-garden-count (-> (garden/get-garden-repo)
(.list-gardens)
count)
None the less, in your particular case you're using all your intermediate variables in your test validation, so you need them on the let statement anyway. Maybe new-garden-id is the only intermediate you can avoid:
fetched-garden (->> (.add-garden repo new-garden)
(.get-garden repo))
Or using the approach suggested by Chiron:
fechted-gaden (.get-garden repo (.add-garden repo new-garden))
Personally, that is how I code in Clojure. Clojure is terse, elegant and concise enough.
I don't think that by compacting to the following is going to be "idiomatic".
(is (= (+ (count (.list-gardens repo)) 1) (count (.list-gardens (garden/get-garden-repo)))))
Your code snippet is easier to understand, to test to debug (in Eclipse, IntelliJ ..).
Clojure is about simplicity and I would like to keep it that way.
Still, answers to your question are highly opinionated.
By looking at your function code it seems that the "things" the function is working with are typical OO objects with getter/setter and methods (see there are lots of .{something} calls), which makes you use these let bindings because of the way the object APIs are designed. Which is fine if you have to work with objects.
In Clojure you basically design your APIs around data structures like map/vector/list/set and functions, which (in most cases) gives you the sort of API which may not require that much let binding usage.
(def evil-code (str "(" (slurp "/mnt/src/git/clj/clojure/src/clj/clojure/core.clj") ")" ))
(def r (read-string evil-code ))
Works, but unsafe
(def r (clojure.edn/read-string evil-code))
RuntimeException Map literal must contain an even number of forms clojure.lang.Util.runtimeException (Util.java:219)
Does not work...
How to read Clojure code (presering all '#'s as themselves is desirable) into a tree safely? Imagine a Clojure antivirus that want to scan the code for threats and wants to work with data structure, not with plain text.
First of all you should never read clojure code directly from untrusted data sources. You should use EDN or another serialization format instead.
That being said since Clojure 1.5 there is a kind of safe way to read strings without evaling them. You should bind the read-eval var to false before using read-string. In Clojure 1.4 and earlier this potentially resulted in side effects caused by java constructors being invoked. Those problems have since been fixed.
Here is some example code:
(defn read-string-safely [s]
(binding [*read-eval* false]
(read-string s)))
(read-string-safely "#=(eval (def x 3))")
=> RuntimeException EvalReader not allowed when *read-eval* is false. clojure.lang.Util.runtimeException (Util.java:219)
(read-string-safely "(def x 3)")
=> (def x 3)
(read-string-safely "#java.io.FileWriter[\"precious-file.txt\"]")
=> RuntimeException Record construction syntax can only be used when *read-eval* == true clojure.lang.Util.runtimeException (Util.java:219)
Regarding reader macro's
The dispatch macro (#) and tagged literals are invoked at read time. There is no representation for them in Clojure data since by that time these constructs all have been processed. As far as I know there is no build in way to generate a syntax tree of Clojure code.
You will have to use an external parser to retain that information. Either you roll your own custom parser or you can use a parser generator like Instaparse and ANTLR. A complete Clojure grammar for either of those libraries might be hard to find but you could extend one of the EDN grammars to include the additional Clojure forms. A quick google revealed an ANTLR grammar for Clojure syntax, you could alter it to support the constructs that are missing if needed.
There is also Sjacket a library made for Clojure tools that need to retain information about the source code itself. It seems like a good fit for what you are trying to do but I don't have any experience with it personally. Judging from the tests it does have support for reader macro's in its parser.
According to the current documentation you should never use read nor read-string to read from untrusted data sources.
WARNING: You SHOULD NOT use clojure.core/read or
clojure.core/read-string to read data from untrusted sources. They
were designed only for reading Clojure code and data from trusted
sources (e.g. files that you know you wrote yourself, and no one
else has permission to modify them).
You should use read-edn or clojure.edn/read which were designed with that purpose in mind.
There was a long discussion in the mailing list regarding the use of read and read-eval and best practices regarding those.
I wanted to point out an old library (used in LightTable) that uses read-stringwith a techniques to propose a client/server communication
Fetch : A ClojureScript library for Client/Server interaction.
You can see in particular the safe-read method :
(defn safe-read [s]
(binding [*read-eval* false]
(read-string s)))
You can see the use of binding *read-eval* to false.
I think the rest of the code is worth watching at for the kind of abstractions it proposes.
In a PR, it is suggested that there is a security problem that can be fixed by using edn instead (...aaand back to your question) :
(require '[clojure.edn :as edn])
(defn safe-read [s]
(edn/read-string s))