Is var in Clojure is stored as an object?
Question 1:
If yes, then object of which class?
Question 2:
In Java, we have references stored on the thread stack and the they refer to the objects stored on process heap.
How to interpret vars in Clojure like the analogy of objects in Java.
EDITS:
To try the first question by myself, I used type/class to check the class of the object.
Case 1:
(def a 100)
(type a)
O/P:
java.lang.Long
In this case, it is clear that a is an object of Long class.
But, how to check the same thing for functions. For example -
case 2:
(type identity)
O/P:
clojure.core$identity
So, from the case 2, type returns the namespace instead of class.
How to get the class?
If you call (type x) on some previously defined x, then you are using the value of x. If you want to find out about the type of the var, you need to look at the var:
user=> (type #'a)
clojure.lang.Var
A naive way to get information about object is the bean function
user=> (bean #'a)
{:watches {}, :validator nil, :public true, :threadBinding nil, :bound true, :dynamic false, :macro false, :class clojure.lang.Var, :rawRoot 42, :tag nil}
Finding out about the hierarchy via parents:
user=> (parents (class #'a))
#{java.io.Serializable clojure.lang.IFn clojure.lang.Settable clojure.lang.IRef clojure.lang.ARef}
Everything in the JVM is an Object-descendant (except the primitive types).
Updated - typed original answer too quickly
The concept of a "Var" is built into the Clojure language/compiler. A Var is normally accessed via a namespaced symbol. Each namespace is implemented like a map, where the map keys are Clojure symbols and the map values are Clojure Var objects.
Each Var object is a mutable object that points to an immutable Clojure "value" (eg 5, [1 2 3], {:a 1 :b 2} etc).
Please see this list of documentation sources, esp "Getting Clojure". For the nitty gritty details, look into the Clojure namespace and its implementation.
Clojure CheatSheet
Related
Clojure empty changes types of Java collections.
For example a JavaParser MethodCallExpr object mce,
(type (.getArguments mce))
;; => com.github.javaparser.ast.NodeList
(type (emtpy (.getArguments mce)))
;; => nil
(type (into (empty (.getArguments mce)) (.getArguments mce)))
;; => clojure.lang.PersistentList
But (.setArguments mce ???) needs ??? to be a NodeList<Expression>, so how to make an object ??? in clojure?
Thanks!
empty works only for classes that implement clojure.lang.IPersistentCollection. It won't work for anything else.
In your case, if you know that the type is NodeList, just construct it yourself via Java interop.
If you don't know that it's NodeList in some general case, you're out of luck because you can't construct an instance of an arbitrary class based on a single assumption that it's a collection class.
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 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.
I could not understand the usage of reify function in Clojure.
What is it used for in clojure?
Could you provide examples?
reify is to defrecord what fn is to defn.
"Ah right...... so what's reify"
Put simply, protocols are lists of functions a datatype should support, records are datatypes and reifications are anonymous datatypes.
Maybe this is long-winded, but reify can't be understood concretely without understanding protocols and types/records: Protocols are a way to use the same name for a function such as conj that actually acts differently when given different arguments ((conj [:b :c] :a) => [:b :c :a] but (conj '(:b :c) :a) => (:a :b :c)). Records are like objects or types (but they act like maps making them awesomer).
More fundamentally, the goal is to solve "The Expression Problem" that is to have the ability to seamlessly add new types of data that work with existing functions, and new functions that work seamlessly with existing data.
So one day you say to yourself, "Self, you should learn what it means to be a duck!" so you write a protocol:
(defprotocol Quacks
(quack [_] "should say something in ducky fashion"))
But it's all too abstract so you 'realify' it:
(def donald (reify Quacks
(quack [_] "Quacks and says I'm Donald")))
Now at last you can experience your creation:
(quack donald) => "Quacks and says I'm Donald"
Then you remember about Daffy:
(def daffy (reify Quacks
(quack [_] (str "Quacks and says I'm Daffy"))))
(quack daffy) => "Quacks and says I'm Daffy"
But by the time you remember about Huey, you realize your mistake and define what a duck is in a reusable way:
(defrecord Duck [name]
Quacks
(quack [_] (str "Quacks and says I'm " name)))
And make new ducks (there are several ways to do it):
(def huey (->Duck "Huey"))
(def duey (Duck. "Duey"))
(def louie (new Duck "Louie"))
(quack huey) => "Quacks and says I'm Huey"
Remember that records act like maps (thank to protocols!):
(:name huey) => "Huey"
But then you remember that ducks must quack and walk so you write another protocol:
(defprotocol Walks
(walk [_] "should walk like a duck"))
And extend the definition of duck
(extend-type Duck
Walks
(walk [_] "waddle waddle"))
(walk louie) => "waddle waddle"
Now we can extend other types to implement the same protocol (teach the same function how to work with other things):
So let's say we want programmers to quack too :-)
(defrecord Programmer [] Quacks
(quack [_] "Monads are simply monoids in a category of endofunctors..."))
(quack (Programmer.)) => "Monads are simply monoids in a category of endofunctors..."
I recommend this great explanation of protocols, an explanation of reify and a chapter on protocols in "Clojure for the Brave and True".
Disclaimer: This is only meant to give an initial understanding of what protocols are, not best practices on how to use them. "Psst! I answered this question largely to teach myself, because until yesterday I had never actually written my own protocol/interface!"
So while I hope that it enhances someone else's learning, I'll heartily welcome criticism or edit-suggestions!".
reify macro allow to create an anonymous class extending java.lang.Object class and/or implementing specified interfaces/protocols. The API docs don't describe the purpose clearly but rather provide the technical details what that macro does. Java interop documentation provides a brief description of the purpose:
As of Clojure 1.2, reify is also available for implementing
interfaces.
Even more information can be found in datatypes documentation where you can find a very detailed description what it does and how it compares to proxy:
While deftype and defrecord define named types, reify defines both an
anonymous type and creates an instance of that type. The use case is
where you need a one-off implementation of one or more protocols or
interfaces and would like to take advantage of the local context. In
this respect it is use case similar to proxy, or anonymous inner
classes in Java.
The method bodies of reify are lexical closures, and can refer to the
surrounding local scope. reify differs from proxy in that:
Only protocols or interfaces are supported, no concrete superclass.
The method bodies are true methods of the resulting class, not
external fns. Invocation of methods on the instance is direct, not
using map lookup. No support for dynamic swapping of methods in the
method map. The result is better performance than proxy, both in
construction and invocation. reify is preferable to proxy in all cases
where its constraints are not prohibitive.
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