What does #^ do? [duplicate] - clojure

This question already has answers here:
Clojure syntax question re: #^
(2 answers)
Closed 9 years ago.
I have looked through Clojure documentation and at source code, however I cannot find the meaning of #^.
What does #^ do in the following, and where is it documented?
(defn- parse-headers [#^HttpResponse http-resp]
(into {} (map (fn [#^Header h] [(.toLowerCase (.getName h)) (.getValue h)])
(iterator-seq (.headerIterator http-resp)))))

It's just supposed to be a type hint, which is usually signified by ^TypeName before the parameter name in a function's parameter list. I'm not sure what the difference is between ^ and #^; maybe it's older syntax?

Related

In Clojure, how would I redefine vars for a lazy sequence? [duplicate]

This question already has answers here:
Clojure binding of dynamic var not working as expected
(3 answers)
Closed 1 year ago.
In a namespace, I have two dynamic vars:
(def ^:dynamic *form-data*)
(def ^:dynamic *form-errors*)
In order to quickly create new bindings for them, I've made a wrapper macros:
(defmacro with-form [data errors & body]
`(binding [*form-data* ~data
*form-errors* ~errors]
~#body))
I have several functions in the same namespace that rely on those vars, one of them is input-field.
It works when I use the function by itself, in a repl. But when I use it this way:
(vf/with-form {} {}
(map #(vf/input-field hf/text-field %) [:name :code]))
I get an error: Attempting to call unbound fn: *form-errors*
I guess the problem is that bindings runs map, creates a lazy seq, and unbounds the vars back to their original state. Is there a way around this limitation?
Thank you.
Use doall to force the entire lazy seq to be realised:
(vf/with-form {} {}
(doall (map #(vf/input-field hf/text-field %) [:name :code])))
This example in the docs for binding illustrates the same technique.
Alternatively, to retain laziness use bound-fn*, as demonstrated by this example in the docs:
(vf/with-form {} {}
(map (bound-fn* #(vf/input-field hf/text-field %)) [:name :code]))
Just to supplement the previous answer, please see this list of documentation sources, especially the Clojure CheatSheet.
In particular, I alway like to use mapv instead of map. It is equivalent to
(vec (map ...))
and it avoids the "gotchas" created by lazy-sequences.

clojure symbol resolve failure in eval [duplicate]

This question already has an answer here:
Variable scope + eval in Clojure
(1 answer)
Closed 3 years ago.
I'm a beginner in clojure.
Could you help with the last 2 expression?
I cannot figure out why "Unable to resolve symbol: result in this context".
Thanks a lot!
(I'm trying to solve a problem in which there are references within list.)
(let [result ['(get result 1) 2]]
(println (get result 1)) ;this can work
(println (eval '(get result 1))) ;error
(println (eval(first result)))) ;error`
I expect (map eval result) to yield [2 2].
eval evaluates the forms you send it in the namespace bound to *ns* but with a blank lexical scope. So surrounding let values are not carried over. Defined vars, dynamic bindings etc however will be there. This post explains it well Variable scope + eval in Clojure
As an aside, eval is pretty powerful and confusing liquor to be sipping on as a beginner. In 6-7 years of programming in clojure I have never needed it.

Clojure variable arguments idiom [duplicate]

This question already has an answer here:
Why such implementation of partial in clojure.core
(1 answer)
Closed 4 years ago.
I'm trying out Clojure using the official guides. Here's my solution to problem 8 of that link, which is to write a function opposite which is supposed to mimic the complement function:
(defn opposite [f] (fn [& args] (not (apply f args))))
For comparison, here's the source code of complement:
(defn complement
"Takes a fn f and returns a fn that takes the same arguments as f,
has the same effects, if any, and returns the opposite truth value."
{:added "1.0"
:static true}
[f]
(fn
([] (not (f)))
([x] (not (f x)))
([x y] (not (f x y)))
([x y & zs] (not (apply f x y zs)))))
Now, my implementation seems to work in simple cases with only a couple of arguments, e.g
user=> (def unequal (opposite =))
#'user/unequal
user=> (unequal 1 2)
true
user=> (unequal 1 1)
false
So my two-part question is:
Is my opposite function equivalent to complement, or does it just
look like it? I.e. are the first three cases for definite numbers of
arguments actually necessary?
If they aren't necessary, is there a reason that the form of the complement
source code is somehow idiomatic Clojure?
Thanks in advance (and hail friendly SO!).
The Clojure source code breaks out the 0, 1, and 2 arg cases for efficiency purposes. They have essentially "pre-compiled" out 3 special cases, plus one general case.
Your code is perfectly legal, and preferred unless a performance bottleneck has been measured & proven (or you are writing a compiler/library like clojure.core).

Arity of anonymous functions in Clojure [duplicate]

This question already has answers here:
How many arguments does an anonymous function expect in clojure?
(3 answers)
Closed 5 years ago.
I'm very new to Clojure and asking myself, how the arity of an anonymous function is defined/deducted.
Please consider the following poor-man count function:
(reduce #(+ 1 %1) 0 '(1 2 3 55))
Running it with clojure I'm getting the following error message:
ArityException Wrong number of args (2) passed to: user/eval1157/fn--1158 clojure.lang.AFn.throwArity (AFn.java:429)
However, it works fine with JavaScript-Clojure and returns 4 as desired (you can execute the command here).
Changing the command by exchanging %1->%2 to
(reduce #(+ 1 %2) 0 '(1 2 3 55))
would compile on both versions (but no longer work as count). In this case seemingly, it can be deduced from %2 that there are at least two arguments.
So which version of Clojure is right? Am I allowed to feed an arbitrary amount of arguments to an anonymous function defined via #(...) or only as many as mentioned inside of this function?
Should it be considered a bug in JavaScript-Clojure?
Edit: As have been explained in comments and in answer, that this is just the way how JavaScript works. There are differences to Java-Clojure, which are documented here, in particular:
There is currently no runtime enforcement of arity when calling a fn
The parameters in the resulting function is determined by the highest numbered used parameter. Thus by using %2 both become a 2 arity function, but since you only use %1 (or %) it becomes a one arity function in both versions of Clojure.
In JavaScript you can pass as many arguments as you'd like and even pass fewer than the parameter list. Variables without matching argument become undefined and arguments without defined parameters are simply not bound and available in the function. ClojureScript would have to add argument checking in each function in order to get the same behavior as in Clojure. It would be a bug if this is the specified behavior. Many transpiled languages does this.
The solution for your example is to not use the short version but rather fn:
(reduce (fn [a _] (+ 1 a)) 0 '(1 2 3 55))

How to call a static method on an incoming class-pointer in Clojure? [duplicate]

This question already has answers here:
Clojure vars and Java static methods
(3 answers)
Closed 8 years ago.
I wanted to get the bit size of bounded primitives in Clojure. These can be found with
(java.lang.Integer/SIZE)
=>32
or the equal, less sweet
(. java.lang.Integer SIZE)
=> 32
(I use java.lang.*-names just for clarity in these examples, they can be omitted)
Of course I wanted to parametrize the call, like
(def integer-class java.lang.Integer)
(. integer-class SIZE)
CompilerException java.lang.RuntimeException: Unable to resolve symbol: intger-class in this context, compiling:(/private/var/folders/yt/g82v06jn63qc5273rx4zjx440000gn/T/form-init4887476821027963248.clj:1:1)
The number of bounded primitives are limited in Java, which makes this exercise a bit academic, but the questions would be:
How do I (dynamically) call a static method in a class given as a var?
As ponzao says, the Clojure vars and Java static methods has an answer with a macro jcall that solves the problem.
(defmacro jcall [obj & args]
(let [ref (if (and (symbol? obj)
(instance? Class (eval obj)))
(eval obj)
obj) ]
`(. ~ref ~#args)))
(jcall java.lang.Integer SIZE) => 32!
Thanks.