I am interested in if it is possible to redefine or override the bindings that are the result of a closure when programming in Clojure?
For example I can do the following just fine:
(defn triple-adder-fn [a b] (fn [x] (+ x a b)))
(def triple-adder (triple-adder-fn 1 2))
(triple-adder 3)
;; => 6
However this creates a local closure that has the bindings of a = 1 and b = 2 and when I call triple-adder it uses them accordingly.
Now the question is could I do something like the following mock code that would allow me to override those local bindings?
(binding ['a 5
'b 6]
(triple-adder 3))
;; => 14
For my simple example it'd be real easy to call the triple-adder-fn to get a new function with new bindings. However, for my actual situation, I am in a position where I don't actually control the triple-adder-fn and only have access to the resulting function.
From your description there is no solution to your problem. Once a closure has "closed over" free params, they can't be changed.
To solve this, you would have to make a new closure, or perhaps redefine triple-adder-fn to use global dynamic vars instead of local parameters. Or, you could copy triple-adder-fn and change the copy to work as you wish.
Related
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
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)
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.
I know that in Java, if I pass an object to a method as an argument, then the method will let the argument variable point to the same object rather than making a duplicate. How about in Clojure? For example:
(defn print-from-reader [rdr]
(print (.read rdr)))
(...inside some code...
(with-open [rdr (Reader file)]
(print-from-rader rdr)))
Does print-from-reader make another copy of rdr in memory when rdr is passed in, or it's pointing to the same rdr that's already created by with-open binding?
And is there any way to check if two clojure instances are pointing to same memory?
Sorry about my bad terms such as "pointing to" and "instances", I am a newbie in Clojure and still learning it. :-)
According to answer to this question on google groups it's pass by value.
Clojure inherits the argument-passing semantics from Java. So it is pass-by-value, where the value passed is an object reference. In addition there are optimization facilities that enable the passing of primitive-typed values.
So functions don't make copies when parameters are passed. rdr in your code will be the same instance.
Makes sense to implement it like that due to java interoperability - otherwise you couldn't (easily) modify java objects' state with its method.
You can test it easily:
(import 'java.util.HashMap)
(def m (new HashMap))
(defn foo [m] (defn bar [m] (.put m "testkey" "testvalue")) (bar m) (println (get m "testkey")))
(foo m)
Results in :
testvalue
nil
If bar created its own copy of m, then the println wouldn't print the value assigned inside bar.
Clojure is pass-by-value just like Java. I think of it as, the references are passed by value.
It isn't a stretch for Clojure to work like this, Scheme and Common Lisp behave the same way.
You can test whether two references point to the same memory with identical?:
(identical? x y)
Tests if 2 arguments are the same object
In Clojure, how to use a java Class that is stored in a variable?
How should I fix the following code?
(def a java.lang.String)
(new a "1"); CompilerException java.lang.IllegalArgumentException: Unable to resolve classname: a
And why this one works fine?
(def a str)
(a "1")
The most elegant solution is to write construct that does the same as new but is able to receive a class dynamically:
(defn construct [klass & args]
(clojure.lang.Reflector/invokeConstructor klass (into-array Object args)))
(def a HashSet)
(construct a '(1 2 3)); It works!!!
This solution overcomes the limitation of #mikera's answer (see comments).
Special Thanks to #Michał Marczyk that made me aware of invokeConstructor answering another question of mine: Clojure: how to create a record inside a function?.
Another option is to store the call to the constructor as an anonymous function. In our case:
(def a #(String. %1))
(a "111"); "111"
When you define a in this way, you get a var containing a java.lang.Class
(def a java.lang.String)
(type a)
=> java.lang.Class
You then have 2 options:
A: Construct the new instance dynamically by finding the Java constructor using the reflection API. Note that as Yehonathan points out you need to use the exact class defined in the constructor signature (a subclass won't work as it won't find the correct signature):
(defn construct [klass & args]
(.newInstance
(.getConstructor klass (into-array java.lang.Class (map type args)))
(object-array args)))
(construct a "Foobar!")
=> "Foobar!"
B: Construct using Clojure's Java interop, which will require an eval:
(defn new-class [klass & args]
(eval `(new ~klass ~#args)))
(new-class a "Hello!")
=> "Hello!"
Note that method A is considerably faster (about 60x faster on my machine), I think mainly because it avoids the overhead of invoking the Clojure compiler for each eval statement.
The problem is that Clojure implements Java interop using a number of special forms:
user=> (doc new)
-------------------------
new
Special Form
Please see http://clojure.org/special_forms#new
nil
this basically means the "normal" Clojure syntax is altered to allow for handier constructs when calling Java. As a naive reflection solution to your dynamic Java needs, you can leverage eval:
user=> (def a String) ; java.lang package is implicitly imported
#'user/a
user=> `(new ~a "test") ; syntax quote to create the correct form
(new java.lang.String "test")
user=> (eval `(new ~a "test")) ; eval to execute
"test"
The same strategy works with all the other interop special forms, like method invocation.
EDIT: look also at the answer from #mikera for a more performing alternative via the Java reflection API.