I am curious if it is possible to write a function in clojure that can be called from the repl without opening and closing parentheses. I use for example always the following function:
(defn ll [] (load-file "D:\\work.clj"))
I have to call this with (ll) but it would come in handy if only ll was needed.
[My idea comes from autocad/autolisp. In there I can define a function like (defun c:somecommand () . . )
From this point on I can use somecommand on the commandline (because of 'c:' before the command. Without parentheses.]
You could, but you shouldn't ;)
Here's an example that misuses (IMHO) reify to override .toString to have a side-effect.
(def m (reify Object (toString [this] (println "Evil side effect") "foo")))
#'user/m
user=> m
Evil side effect
#object[user$reify__151 0x3350ebdd "foo"]
Related
I'm trying to find a way to thread a value through a list of functions.
Firstly, I had a usual ring-based code:
(defn make-handler [routes]
(-> routes
(wrap-json-body)
(wrap-cors)
;; and so on
))
But this was not optimal as I wanted to write a test to check the routes are actually wrapped with wrap-cors. I decided to extract the wrappers into a def. So the code became as follows:
(def middleware
(list ('wrap-json-body)
('wrap-cors)
;; and so on
))
(defn make-handler [routes]
(-> routes middleware))
This apparently doesn't work and is not supposed to as the -> macro doesn't take a list as the second argument. So I tried to use the apply function to resolve that:
(defn make-handler [routes]
(apply -> routes middleware))
Which eventually bailed out with:
CompilerException java.lang.RuntimeException: Can't take value of a
macro: #'clojure.core/->
So the question arises: How does one pass a list of values to the -> macro (or, say, any other macro) as one would do with apply for a function?
This is an XY Problem.
The main point of -> is to make code easier to read. But if one writes a new macro solely in order to use -> (in code nobody will ever see because it exists only at macro-expansion), it seems to me that this is doing a lot of work for no benefit. Moreover, I believe it obscures, rather than clarifies, the code.
So, in the spirit of never using a macro where functions will do, I suggest the following two equivalent solutions:
Solution 1
(reduce #(%2 %) routes middleware)
Solution 2
((apply comp middleware) routes)
A Better Way
The second solution is easily simplified by changing the definition of middleware from being a list of the functions to being the composition of the functions:
(def middleware
(comp wrap-json-body
wrap-cors
;; and so on
))
(middleware routes)
When I began learning Clojure, I ran across this pattern often enough that many of my early projects have an freduce defined in core:
(defn freduce
"Given an initial input and a collection of functions (f1,..,fn),
This is logically equivalent to ((comp fn ... f1) input)."
[in fs]
(reduce #(%2 %) in fs))
This is totally unnecessary, and some might prefer the direct use of reduce as being more clear. However, if you don't like staring at #(%2 %) in your application code, adding another utility word to your language is fine.
you can make a macro for that:
;; notice that it is better to use a back quote, to qoute function names for macro, as it fully qualifies them.
(def middleware
`((wrap-json-body)
(wrap-cors))
;; and so on
)
(defmacro with-middleware [routes]
`(-> ~routes ~#middleware))
for example this:
(with-middleware [1 2 3])
would expand to this:
(-> [1 2 3] (wrap-json-body) (wrap-cors))
I'm doing my first steps with Clojure today and I encountered the first confusing obstacle right off the bat!
I've built a new Leiningen(2.5.1) project and just want to run the default code, which is:
(ns wavescript.core
(:gen-class))
(defn -main
"I don't do a whole lot ... yet."
[& args]
(println "Hello, World!"))
Problem is the Lighttable(0.7.2) console tells:
WARNING: unsigned-bit-shift-right already refers to:
#'clojure.core/unsigned-bit-shift-right in namespace: cljs.core,
being replaced by: #'cljs.core/unsigned-bit-shift-right
I found some Google entries but none brought me further. What this is about?
This is caused by the symbol unsigned-bit-shift-right being found in the clojure.core namespace as well as a cljs.core. The clojure.core namespace is compiled/loaded before cljs.core, and the introduction of the new symbol is throwing the warning. It looks like, from the namespace, you are writing clojurescript. If you look at this file cljs.core on line 2147, you will see this form:
(defn unsigned-bit-shift-right
"Bitwise shift right with zero fill"
[x n] (cljs.core/unsigned-bit-shift-right x n))
in the cljs.core namespace. So, apparently, lighttable is importing both clojure.core and clj.core.
Honestly, I am not even sure how the cljs implementation is working, as it is completely self-referential. Additionally, there are uses of unsigned-bit-shift-right starting at line 451 that are not prefixed, so they must be using the clojure.core implementation. Bizarre. The above form appears after all the previous uses. It looks safe to say that symbol can be safely excluded. In fact, this may deserve a patch...
To resolve this, you might want to try to explicitly state your namespace importations and exclude that import. The refer function affords that.
So, you would have a namespace that looks like this
(ns my.namespace.hello-world
[:require
[cljs.core :exclude [unsigned-bit-shift-right]]])
The clojure.core implementation looks like this:
(defn unsigned-bit-shift-right
"Bitwise shift right, without sign-extension."
{:inline (fn [x n] `(. clojure.lang.Numbers (unsignedShiftRight ~x ~n)))
:added "1.6"}
[x n] (. clojure.lang.Numbers unsignedShiftRight x n))
Alternately, since they are wrapping the functionality, perhaps cljs.core is designed to not need to expose clojure.core. If that is the case, then exclude clojure.core, and see if you code will function properly.
In fact, from looking at the cljs.core namespace:
(ns cljs.core
(:refer-clojure :exclude [-> ->> .. amap and areduce alength aclone assert binding bound-fn case comment cond condp
declare definline definterface defmethod defmulti defn defn- defonce
defprotocol defrecord defstruct deftype delay destructure doseq dosync dotimes doto
extend-protocol extend-type fn for future gen-class gen-interface
if-let if-not import io! lazy-cat lazy-seq let letfn locking loop
memfn ns or proxy proxy-super pvalues refer-clojure reify sync time
when when-first when-let when-not while with-bindings with-in-str
with-loading-context with-local-vars with-open with-out-str with-precision with-redefs
satisfies? identical? true? false? number? nil? instance? symbol? keyword? string? str get
make-array vector list hash-map array-map hash-set
aget aset
+ - * / < <= > >= == zero? pos? neg? inc dec max min mod
byte char short int long float double
unchecked-byte unchecked-char unchecked-short unchecked-int
unchecked-long unchecked-float unchecked-double
unchecked-add unchecked-add-int unchecked-dec unchecked-dec-int
unchecked-divide unchecked-divide-int unchecked-inc unchecked-inc-int
unchecked-multiply unchecked-multiply-int unchecked-negate unchecked-negate-int
unchecked-subtract unchecked-subtract-int unchecked-remainder-int
unsigned-bit-shift-right
bit-and bit-and-not bit-clear bit-flip bit-not bit-or bit-set
bit-test bit-shift-left bit-shift-right bit-xor
cond-> cond->> as-> some-> some->>
if-some when-some test ns-interns var vswap!])
You can see that unsigned-bit-shift-right is supposed to be excluded from the namespace. So, you will want to exclude clojure.core to resolve the problem.
What's the (most) idiomatic Clojure representation of no-op? I.e.,
(def r (ref {}))
...
(let [der #r]
(match [(:a der) (:b der)]
[nil nil] (do (fill-in-a) (fill-in-b))
[_ nil] (fill-in-b)
[nil _] (fill-in-a)
[_ _] ????))
Python has pass. What should I be using in Clojure?
ETA: I ask mostly because I've run into places (cond, e.g.) where not supplying anything causes an error. I realize that "most" of the time, an equivalent of pass isn't needed, but when it is, I'd like to know what's the most Clojuric.
I see the keyword :default used in cases like this fairly commonly.
It has the nice property of being recognizable in the output and or logs. This way when you see a log line like: "process completed :default" it's obvious that nothing actually ran. This takes advantage of the fact that keywords are truthy in Clojure so the default will be counted as a success.
There are no "statements" in Clojure, but there are an infinite number of ways to "do nothing". An empty do block (do), literally indicates that one is "doing nothing" and evaluates to nil. Also, I agree with the comment that the question itself indicates that you are not using Clojure in an idiomatic way, regardless of this specific stylistic question.
The most analogous thing that I can think of in Clojure to a "statement that does nothing" from imperative programming would be a function that does nothing. There are a couple of built-ins that can help you here: identity is a single-arg function that simply returns its argument, and constantly is a higher-order function that accepts a value, and returns a function that will accept any number of arguments and return that value. Both are useful as placeholders in situations where you need to pass a function but don't want that function to actually do much of anything. A simple example:
(defn twizzle [x]
(let [f (cond (even? x) (partial * 4)
(= 0 (rem x 3)) (partial + 2)
:else identity)]
(f (inc x))))
Rewriting this function to "do nothing" in the default case, while possible, would require an awkward rewrite without the use of identity.
Instead of:
(run-jetty (fn [request] (response "hello")) 6789)
I want (to ignore the give parameter):
(run-jetty #(response "hello") 6789)
I.e., I want to use anonymous function to save a few typing. Clearly it will raise error at runtime as the the anonymous function will be given a parameter(i.e., request) which it doesn't want to handle . So what is the idiomatic way to achieve that ?
It depends on your exact use, but I would the constantly function.
(run-jetty (constantly (response "hello")) 6789)
If you're trying to delay the computation with an anonymous function then this won't work (hint: use delay and force in that case), but for ring handlers it will work nicely.
I found my question is duplicated with this one.
Also I found the constantly is really constant : It will cache the result for the subsequence usage. Although it's not what I want, it's good to know:
demo1.core=> (defn foo [] (rand))
#'demo1.core/foo
demo1.core=> (def aa (constantly (foo)))
#'demo1.core/aa
demo1.core=> (aa)
0.8006471724049917
demo1.core=> (aa 1)
0.8006471724049917
demo1.core=> (aa 1 2)
0.8006471724049917
Just in case somebody else like me are looking for same thing.
Occasionally when looking at other people's Clojure code, I see a function defined via defn and then called using the var-quote syntax, e.g.:
user> (defn a [] 1)
#'user/a
user> (a) ; This is how you normally call a function
1
user> (#'a) ; This uses the var-quote syntax and produces the same result
1
For the life of me I can't figure out the difference between these two ways of calling a function. I can't find anything in the evaluation documentation to say what happens when the operator of a call is a var that might suggest why the second form would be preferred. They both seem to respond in the same to binding assignments and syntax-quoting.
So, can somebody please provide a code sample that will illustrate the difference between (a) and (#'a) above?
Edit: I know that var-quote can be used to get to a var that's shadowed by a let lexical binding, but that doesn't seem to be the case in the code that I'm looking at.
(#'a) always refers to the var a, while (a) can be shadowed by local bindings:
user> (defn a [] 1)
#'user/a
user> (let [a (fn [] "booh")] [(a) (#'a)])
["booh" 1]
But most actual uses of var-quote / function call are not calling the var-quote expression directly, but instead cache its value so that higher-order constructs refer to the current value of var a instead of its value when passed in:
(defn a [] 1)
(defn my-call [f] (fn [] (+ 1 (f))))
(def one (my-call a))
(def two (my-call #'a))
(defn a [] 2)
user> (one)
2
user> (two)
3
This is mostly useful for interactive development, where you're changing some function that gets wrapped in a bunch of other functions in other packages.
The second form allows you to circumvent the privacy restrictions that clojure puts in place.
So, for instance, if you develop a library with private functions, but want to test them from a separate namespace, you cannot refer to them directly. But you can get to them using the var quote syntax. It's very useful for this.
Privacy is clojure is, in essence, a form of automatic documentation, as opposed to the privacy you see in Java. You can get around it.
user> (defn- a [] 1)
#'user/a
user> (ns user2)
nil
user2> (user/a)
CompilerException java.lang.IllegalStateException: var: #'user/a is not public, compiling:(NO_SOURCE_PATH:1)
user2> (#'user/a)
1
user2>