How does Clojure ^:const work?

That looks like a bad example to me, since the stuff about map-lookup just confuses the issue. A more realistic example would be: (def pi 3.14) (defn circ [r] (* 2 pi r)) In this case, the body of circumference is compiled into code that dereferences pi at runtime (by calling Var.getRawRoot), each time circumference … Read more

Executing multiple statements in if-else without nullpointer exception

Use do: (defn status [] (if server (do (println “server is up and running”) (println “connections:” (connection-count server))) (println “server is down”))) In Lisps, generally, you can’t just add parens for grouping. ((println “foo”) (println “foo”)) Here, the return value of the first (println “foo”) will be tried to be called (as a function), with … Read more

How to handle java variable length arguments in clojure?

Since Java varargs are actually arrays, you can call vararg functions in Clojure by passing an array. You could convert a Clojure seq (maybe by using Clojure’s variety of variable argument functions) into an array: (TestClass/aStaticFunction (into-array Integer [(int 1),(int 2)])) or (defn a-static-function-wrapper [& args] (TestClass/aStaticFunction (into-array Integer args)) Or make an array and … Read more

Absolute value of a number in Clojure

As of Clojure 1.11, it is simply (abs -1) in both Clojure and Clojurescript. In versions before, for double, float, long and int you can use the java.lang.Math method abs (Math/abs -1) Take care it won’t work for decimals, ratio’s, bigint(eger)s and other Clojure numeric types. The official clojure contrib math library that tries guarantee … Read more

Difference between Symbols and Vars in Clojure

There’s a symbol + that you can talk about by quoting it: user=> ‘+ + user=> (class ‘+) clojure.lang.Symbol user=> (resolve ‘+) #’clojure.core/+ So it resolves to #’+, which is a Var: user=> (class #’+) clojure.lang.Var The Var references the function object: user=> (deref #’+) #<core$_PLUS_ clojure.core$_PLUS_@55a7b0bf> user=> @#’+ #<core$_PLUS_ clojure.core$_PLUS_@55a7b0bf> (The @ sign is … Read more

How to get user input in Clojure?

read-line is the correct function.. (println (read-line)) ..would basically echo the users input: Clojure 1.0.0- user=> (println (read-line)) this is my input this is my input To use it in an if statement, you’d probably use let: (let [yayinput (read-line)] (if (= yayinput “1234”) (println “Correct”) (println “Wrong”))) Hope that’s enough to get you started, … Read more

How do we do both left and right folds in Clojure?

The reason that the clojure standard library only has fold-left (reduce) is actually very subtle and it is because clojure isn’t lazy enough to get the main benefit of fold-right. The main benefit of fold-right in languages like haskell is that it can actually short-circuit. If we do foldr (&&) True [False, True, True, True, … Read more