unbound functions in clojure - How to bind them? - clojure

I am trying to deploy a topology on a storm server and it keeps telling me the following:
java.lang.RuntimeException: java.lang.IllegalStateException: Attempting to call unbound fn: #'storm-nblabla/operation-bolt__ at backtype.storm.clojure.ClojureBolt.prepare(ClojureBolt.java:60) a
So I guess I have to bind a function that I am using in the prepare function. So my question is How do you generally bind functions in clojure?
Regards,
Horace

In clojure, a value is usually bound in one of two ways:
locals, without a namespace qualifier, (usually in a let statement or fn / loop args)
This is for values that aren't referenced outside the scope of the block (except if they are provided as an argument to a function inside the block or in the return value of the block).
vars, with namespace scope, usually using def (or a secondary macro like defn)
This is for values that should be accessible at namespace scope, which will be accessible wherever you can access the namespace.
The error (trying to call an unbound fn) is caused by using declare to create a var, and then calling it without providing a true definition:
user> (declare foo)
#'user/foo
user> (foo)
IllegalStateException Attempting to call unbound fn: #'user/foo clojure.lang.Var$Unbound.throwArity (Var.java:43)
In this code the var exists (declare created it), but no value has been assigned.
So you need the latter kind of binding, a var binding:
user> (defn foo [] "OK")
#'user/foo
user> (foo)
"OK"
user>
Somewhere, some part of your code or the code of the library you are using has declared a var, which should be bound to a callable value, but has not been properly initialized. Does the library have an init function of some sort that you haven't called? Maybe there is a namespace you need to require before the definition is visible?

Related

How to print the value of the references of the objects in Clojure?

Whenever I type the following on the REPL
(defn test_function
[]
()
)
The output is -
#'clojure.repl/test_function
As functions are objects in Clojure, how to get the value of the reference that refers to this function object?
In Clojure, a Var (the Java class is clojure.lang.Var) is a container in which you can store any immutable value. You can even store a different immutable value into this container at a later time - but, for now, let's ignore that. The container can be referred to using a name (aka symbol). The mapping between the name and the Var is stored in each namespace. So, when you say
(defn testf [] ())
that is (more or less) equivalent to
(def testf (fn [] ()))
That will create a Var, store the newly created function object into that Var, and create a mapping between the symbol testf and the Var. You can get the function object by just evaluating the symbol. Thus
user=> testf
#object[user$test_function 0x67207d8a "user$testf#67207d8a"]
user=> (class testf)
user$testf
That tells you that the function is a Java object of the class user$testf.
If you want to inspect the Var itself (rather than the value that it contains), you can do the following
user=> (var testf)
#'user/testf
user=> (class (var testf))
clojure.lang.Var
which tells you that the Var is #'user/testf and the Java class that implements a Clojure Var is clojure.lang.Var.
You might benefit from reading Clojure - Vars and the Global Environment or the sources for more details.
To finally answer your question ... you can consider the Var as the holder to a reference to the object. In that case, you can "print" the Var that is bound to a symbol foo by evaluating (var foo). And you can "print" the object itself by evaluating foo.
Clojure compiles your code down to JVM byte code if you load source
files and there is no way around to create classes to do that
(everything except primitive types is an Object descendant in the JVM).
You can see lot's of what is going on, if you check out an uberjar of
your lein project or if you AOT compile clj files.
You can get the class from your function:
(defn test-function []
(println :hello))
(println (class test-function))
; ⇒ user$test_function
The $ indicates, that there is an inner class used; this is just
a convention. Also the - has changed to a _, which clojure calls
"munging".
Now you can create a new instance of that class and you can .invoke it
(as it's implements the
IFn
interface):
(let [tf (new user$test_function)]
(.invoke tf))
; ⇒ :hello

Correct def for expression

I have this function:
(defn get-validator []
(UrlValidator. (into-array ["https"])))
I want it to be evaluated only once, on the first call, then just return the result. Which is the better way to write it:
(def get-validator (UrlValidator. (into-array ["https"])))
(def ^:const get-validator (UrlValidator. (into-array ["https"])))
(defonce get-validator (UrlValidator. (into-array ["https"])))
Or is there another way that is better? Documentation suggests that defonce is the correct one, but it's not clearly stated.
First of all, def sets a var with the given name and optionally the
given "init" value in that var, when the namespace is loaded/compiled
(note that there is basically not much of a difference between loading
and compiling and that's the reason, why you don't want to have
side-effects in your def).
Roughly all three versions are the same, with the following differences:
:^const allows inlining this value; so this effects the following
forms, when they are compiled and might improve performance in the
following code
defonce prevents re-def-ining the var again once the namespace is
reloaded; this is most useful if you def mutable state, that you
want to survive over reloading your code
In any case, requiring the ns for the first time, will execute the code
to init the var. Then it is basically left alone (imagine a static
property in a Java class with a static initializer).
All that said: if UrlValidator has internal state you might still be
better off using a function to create a fresh one, whenever you need it.
Another approach, assuming UrlValidator. is referentially transparent, is to use clojure.core/memoize.
So
(defn get-validator []
(UrlValidator. (into-array ["https"])))
(def uval (memoize get-validator))
And then use (uval) whenever you need the validator. Because of the memoization, get-validator will be called only once.
This approach will make only one call to UrlValidator. the first time (uval) is executed. All the other suggestions will call UrlValidator., once, when the namespace is loaded.

Checking Clojure pre-conditions without running the function?

I have one function that does some (possibly lengthy) work (defn workwork [x] ...) and some other functions to check if the call will succeed ahead of time (defn workwork-precondition-1 [x] ...).
The precondition functions should be evaluated every time workwork is called (e.g. using :pre). The precondition functions should also be collected (and:ed) in a single function and made available to client code directly (e.g. to disable a button).
Which is the idiomatic way to solve this in Clojure while avoiding code duplication?
In particular, is there any way to evaluate the pre-conditions of a function without running the function body?
You can just collect your preconditions into a function:
(defn foo-pre [x]
(even? x))
Then call the function in a :pre-style precondition:
(defn foo [x]
{:pre [(foo-pre x)]}
…)
For functions introduced using defn, you can extract the :pre-style preconditions from the metadata on the Var:
(-> #'foo meta :arglists first meta)
;= {:pre [(foo-pre x)]}
And similarly for the :arglists entries for any other arities.
There are two caveats here:
The automatically-generated :arglists entry in the Var's metadata maybe be overridden. Overriding :arglists results in the above kind of useful automatically-generated metadata to be thrown out.
The {:pre [(foo-pre x)]} value returned by the above (-> #'foo meta …) expression contains foo-pre as a literal symbol – it'd be your responsibility to figure out which function it referred to at foo's point of definition. (This may or may not be possible – for example foo could be defn'd inside a top-level let or letfn form, with foo-pre a local function.)
And finally, anonymous functions may use :pre and :post, but there is currently no mechanism for extracting them from the function itself.
to evaluate the function precondition without running the function body,you can use robert-hooke library https://github.com/technomancy/robert-hooke/
(use 'robert.hooke)
(defn workwork [x] ...)
(defn workwork-precondition-1
[f x]
(if (precondition-1-satisfied? x)
(f x)
:precondition-1-not-satisfied))
(add-hook #'workwork #'workwork-precondition-1)

Can I partial a Java method invocation in Clojure?

I have a method on an object.
myObject.myMethod(1)
I can invoke this in Clojure
(.myMethod myObject 1)
I can also invoke it using information from the lexical environment
(let [x 1] (.myMethod myObject x))
Can I do this with a partial? E.g.
(let [myPartial (partial .myMethod myObject)]
(myPartial 1))
This gives me a
java.lang.RuntimeException: Unable to resolve symbol: .myMethod in this context
I'm currently making this work with an anonymous function
(let [myThing #(.myMethod myObject %)]
(myThing 1))
But if it would be nice to use a partial in this case. Is it possible?
I'm sure the answer will be to do with binding and dispatch but I don't yet have a feeling for where during the compiling and execution the dispatch happens.
You can have partial in your case, use (memfn).
(memfn myMethod args)
In the REPL:
user=> (doc memfn)
-------------------------
clojure.core/memfn
([name & args])
Macro
Expands into code that creates a fn that expects to be passed an
object and any args and calls the named instance method on the
object passing the args. Use when you want to treat a Java method as
a first-class fn. name may be type-hinted with the method receiver's
type in order to avoid reflective calls.

Clojure .get and its difference to get

What is .get in clojure and what is its difference with get?
I know what get does but have never seen .get before.
That's how you invoke a .get method of an instance/class passed as a second parameter.
Eg:
(.get foo) ;; invokes an instance method of a foo object
(.get Bar) ;; invokes a static method of a Bar class
while
(get ...) ;; invokes a clojure get function
References:
http://clojure.org/java_interop