I have a big problem that I couldn't solve and I really do not find the error.
I want to use this function :
http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/optim/univariate/BrentOptimizer.html
The sample Test code from Apache is that :
(source : https://github.com/apache/commons-math/blob/3.6-release/src/test/java/org/apache/commons/math3/optim/univariate/BrentOptimizerTest.java )
public void testSinMin() {
UnivariateFunction f = new Sin();
UnivariateOptimizer optimizer = new BrentOptimizer(1e-10, 1e-14);
Assert.assertEquals(3 * Math.PI / 2, optimizer.optimize(new MaxEval(200),
new UnivariateObjectiveFunction(f),
GoalType.MINIMIZE,
new SearchInterval(4, 5)).getPoint(), 1e-8);
So I tried to reproduce the code with Clojure and another function :
(defn atomic-apache-peak-value [x]
(let [lamb ((x :parameters) 0)
x0 ((x :parameters) 1)
f (D2Sigmoid. lamb x0)
optimizer (BrentOptimizer. 0.0001 0.0001)
maxeval (MaxEval. 1000)
of (UnivariateObjectiveFunction. f)
goal (GoalType/MINIMIZE)
interval (SearchInterval. x0 (* 2 x0))]
(-> (.optimize optimizer maxeval of goal interval)
(.getPoint))))
Clojure tells me "No matching method found : optimize for class ....BrentOptimizer"
I tried to compute the lines of code one by one in the let and it works, so the problem is optimize.
The method is implemented on superclassses sor I imported them
[org.apache.commons.math3.optim.univariate UnivariateOptimizer BrentOptimizer UnivariateObjectiveFunction SearchInterval]
[org.apache.commons.math3.optim BaseOptimizer MaxEval]
It does not change anything.
Do you think I have a syntax problem or a bug or just a wrong way to do ?
Thanks
EDIT :
Forgot to mention that the
(.optimize optimizer)
version throws an exception from Apache but is found. So I do not think Clojure cannot find source code.
Maybe there a problem of syntax ?
Also tried Goaltype/MINIMIZE without parenthesis
EDIT 2 :
Final working code
(defn atomic-apache-peak-value [x]
(let [lamb ((x :parameters) 0)
x0 ((x :parameters) 1)
f (D2Sigmoid. lamb x0)
optimizer (BrentOptimizer. 0.0001 0.0001)
maxeval (MaxEval. 1000)
of (UnivariateObjectiveFunction. f)
goal GoalType/MINIMIZE
interval (SearchInterval. x0 (* 2 x0))]
(-> (.optimize optimizer (into-array OptimizationData [maxeval of goal interval]))
(.getPoint))))
OK, let's create a proper answer. When calling Java methods from Clojure, it is important to look up the actual signature for the method. Just copying from Java sample code may not always work. That is mostly due vargars. Java interop in Clojure requires the programmer to do a bit of additional work when varargs are involved.
The signature of the optimize method you are trying to call is:
public UnivariatePointValuePair optimize(OptimizationData... optData)
throws TooManyEvaluationsException
Notice the ..., which means that the method takes 0 or more arguments of type OptimizationData. In Java, this method can be invoked as optimize(foo, bar, baz) as long as the classes of foo, bar, and baz implement the OptimizationData interface.
However, such handling of the vararg is mostly due to Java compiler. Under the covers, the method actually expects a single argument of type OptimizationData [] - array of OptimizationData. The Java compiler generates code that packs the arguments into an array, the programmer does not have to worry about it.
But when calling such methods from Clojure, the programmer has to create the array. It is as if the signature of that method appears to the Clojure compiler as optimize(OptimizationData[] optData).
It does not take a lot to create an array in Clojure. One way to do it is to use the into-array function. The following shows the necessary bits and pieces:
(import '(org.apache.commons.math3.optim OptimizationData))
(.optimize (into-array OptimizationData [optimizer maxeval of goal interval]))
Also, there is not need to the parenthesis around GoalType/MINIMIZE. The parenthesis mean a list, and lists are evaluated in Clojure as function invocation. Here we do not need to invoke GoalType/MINIMIZE function, we just need that value.
Related
I am trying to define a very simple piecewise linear function in Z3 with the following C++ code:
context c;
sort I = c.int_sort();
expr x = c.int_const("x");
func_decl f = function("f", I, I);
solver s(c);
s.add(forall(x, f(x) == ite(x <= 2, x, x + 1)));
s.add(f(x) == 2);
std::cout << s.check() << std::endl;
This generates the following code in SMTLib format:
(declare-fun f (Int) Int)
(declare-fun x () Int)
(assert (forall ((x Int)) (! (= (f x) (ite (<= x 2) x (+ x 1))) :weight 0)))
(assert (= (f x) 2))
(check-sat)
The obvious answer is x=2. However, during execution, Z3 seems to have entered an infinite loop and stops responding entirely.
Why does this happen, and how should I properly define a piecewise function in Z3?
Malte described some of the issues that crop up often in handling quantifiers. It's almost always a bad idea to use quantifiers to define functions like this: It unnecessarily invokes procedures that can easily lead the solver to never-ending e-matching loops. The classic (and "official") way to define such a function is to simply use the define-fun construct:
(declare-fun x () Int)
(define-fun f ((x Int)) Int (ite (<= x 2) x (+ x 1)))
(assert (= (f x) 2))
(check-sat)
With this input, I get:
sat
immediately.
There's much to say about quantifiers in SMT solving, and here's a good set of slides to go through: http://homepage.divms.uiowa.edu/~ajreynol/pres-dagstuhl15.pdf
But, long story short, avoid quantifiers unless you absolutely need them. For regular first-order problems like the one you have you don't need quantifiers.
(Note that when you program using the C++, or any other higher-level API, you usually do not define these sorts of functions. Instead, you simply define a function in the host language, and call it with a "symbolic" variable, which generates the right-hand-side for each instantiation. In a sense, you "inline" the definitions at each call site. This avoids unnecessary complexity and is usually sufficient for most modeling problems.)
Since SMT problems are often undecidable (depending on which theories the problem involves), it is in general to be expected that Z3 won't terminate (in reasonable time) for certain problems. Quantifiers and non-linear integer arithmetic are, e.g. common causes.
By default, Z3 analysis the problem it was given and configures (e.g. chooses subsolvers) itself accordingly. If you'd like to disable this, e.g. because you want to configure Z3 yourself. use (set-option :auto_config false).
Turning to your example:
Using Z3 4.8.7 x64, I immediately get sat for the SMT-LIB snippet you provided. Which Z3 version are you using?
If I disable MBQI (Z3 has different subsolvers for quantifiers) via (set-option :smt.mbqi true), then I immediately get unknown. This is not terribly surprising because MBQI is great for finding models for (non-recursive) functions, such your f.
Why did you set :weigh 0? It is used to prevent infinite quantifier instantiation chains (matching loops), so explicitly setting a weight of 0 seems risky. Although your quantifier does not give rise to a matching loop anyway.
Macros do not evaluate their arguments until explicitly told to do so, however functions do. In the following code:
(defmacro foo [xs]
(println xs (type xs)) ;; unquoted list
(blah xs))
(defn blah [xs] ;; xs is unquoted list, yet not evaluated
(println xs)
xs)
(foo (+ 1 2 3))
It seems that blah does not evaluate xs, since we still have the entire list: (+ 1 2 3) bound to xs in the body of blah.
I have basically just memorized this interaction between helper functions within macros and their evaluation of arguments, but to be honest it goes against what my instincts are (that xs would be evaluated before entering the body since function arguments are always evaluated).
My thinking was basically: "ok, in this macro body I have xs as the unevaluated list, but if I call a function with xs from within the macro it should evaluate that list".
Clearly I have an embarassingly fundamental misunderstanding here of how things work. What am I missing in my interpretation? How does the evaluation actually occur?
EDIT
I've thought on this a bit more and it seems to me that maybe viewing macro arguments as "implicitly quoted" would solve some confusion on my part.
I think I just got mixed up in the various terminologies, but given that quoted forms are synonymous with unevaluated forms, and given macro arguments are unevaluated, they are implicitly quoted.
So in my above examples, saying xs is unquoted is somewhat misleading. For example, this macro:
(defmacro bluh [xs]
`(+ 1 2 ~xs))
Is basically the same as the below macro (excluding namespacing on the symbols). Resolving xs in the call to list gives back an unevaluated (quoted?) list.
(defmacro bleh [xs]
(list '+ '1 '2 xs)) ;; xs resolves to a quoted list (or effectively quoted)
Calling bleh (or bluh) is the same as saying:
(list '+ '1 '2 '(+ 1 2 3))
;; => (+ 1 2 (+ 1 2 3))
If xs did not resolve to a quoted list, then we would end up with:
(list '+ '1 '2 (+ 1 2 3))
;; => (+ 1 2 6)
So, in short, macro arguments are quoted.
I thnk part of my confusion came from thinking about the syntax quoted forms as templates with slots filled in e.g. (+ 1 2 ~xs) I would mentally expand to (+ 1 2 (+ 1 2 3)), and seeing that (+ 1 2 3) was not quoted in that expansion, I found it confusing that function calls using xs (in the first example above blah) would not evalute immediately to 6.
The template metaphor is helpful, but if I instead look at it as a
shortcut for (list '+ '1 '2 xs) it becomes obvious that xs must be a quoted list otherwise the expansion would include 6 and not the entire list.
I'm not sure why I found this so confusing... have I got this right or did I just go down the wrong path entirely?
[This answer is an attempt to explain why macros and functions which don't evaluate their arguments are different things. I believe this applies to macros in Clojure but I am not an expert on Clojure. It's also much too long, sorry.]
I think you are confused between what Lisp calls macros and a construct which modern Lisps don't have but which used to be called FEXPRs.
There are two interesting, different, things you might want:
functions which, when called, do not immediately evaluate their arguments;
syntax transformers, which are called macros in Lisp.
I'll deal with them in order.
Functions which do not immediately evaluate their arguments
In a conventional Lisp, a form like (f x y ...), where f is a function, will:
establish that f is a function and not some special thing;
get the function corresponding to f and evaluate x, y, & the rest of the arguments in some order specified by the language (which may be 'in an unspecified order');
call f with the results of evaluating the arguments.
Step (1) is needed initially because f might be a special thing (like, say if, or quote), and it might be that the function definition is retrieved in (1) as well: all of this, as well as the order that things happen in in (2) is something the language needs to define (or, in the case of Scheme say, leave explicitly undefined).
This ordering, and in particular the ordering of (2) & (3) is known as applicative order or eager evaluation (I'll call it applicative order below).
But there are other possibilities. One such is that the arguments are not evaluated: the function is called, and only when the values of the arguments are needed are they evaluated. There are two approaches to doing this.
The first approach is to define the language so that all functions work this way. This is called lazy evaluation or normal order evaluation (I'll call it normal order below). In a normal order language function arguments are evaluated, by magic, at the point they are needed. If they are never needed then they may never be evaluated at all. So in such a language (I am inventing the syntax for function definition here so as not to commit CL or Clojure or anything else):
(def foo (x y z)
(if x y z))
Only one of y or z will be evaluated in a call to foo.
In a normal order language you don't need to explicitly care about when things get evaluated: the language makes sure that they are evaluated by the time they're needed.
Normal order languages seem like they'd be an obvious win, but they tend to be quite hard to work with, I think. There are two problems, one obvious and one less so:
side-effects happen in a less predictable order than they do in applicative order languages and may not happen at all, so people used to writing in an imperative style (which is most people) find them hard to deal with;
even side-effect-free code can behave differently than in an applicative order language.
The side-effect problem could be treated as a non-problem: we all know that code with side-effects is bad, right, so who cares about that? But even without side-effects things are different. For instance here's a definition of the Y combinator in a normal order language (this is kind of a very austere, normal order subset of Scheme):
(define Y
((λ (y)
(λ (f)
(f ((y y) f))))
(λ (y)
(λ (f)
(f ((y y) f))))))
If you try to use this version of Y in an applicative order language -- like ordinary Scheme -- it will loop for ever. Here's the applicative order version of Y:
(define Y
((λ (y)
(λ (f)
(f (λ (x)
(((y y) f) x)))))
(λ (y)
(λ (f)
(f (λ (x)
(((y y) f) x)))))))
You can see it's kind of the same, but there are extra λs in there which essentially 'lazify' the evaluation to stop it looping.
The second approach to normal order evaluation is to have a language which is mostly applicative order but in which there is some special mechanism for defining functions which don't evaluate their arguments. In this case there often would need to be some special mechanism for saying, in the body of the function, 'now I want the value of this argument'. Historically such things were called FEXPRs, and they existed in some very old Lisp implementations: Lisp 1.5 had them, and I think that both MACLISP & InterLisp had them as well.
In an applicative order language with FEXPRs, you need somehow to be able to say 'now I want to evaluate this thing', and I think this is the problem are running up against: at what point does the thing decide to evaluate the arguments? Well, in a really old Lisp which is purely dynamically scoped there's a disgusting hack to do this: when defining a FEXPR you can just pass in the source of the argument and then, when you want its value, you just call EVAL on it. That's just a terrible implementation because it means that FEXPRs can never really be compiled properly, and you have to use dynamic scope so variables can never really be compiled away. But this is how some (all?) early implementations did it.
But this implementation of FEXPRs allows an amazing hack: if you have a FEXPR which has been given the source of its arguments, and you know that this is how FEXPRs work, then, well, it can manipulate that source before calling EVAL on it: it can call EVAL on something derived from the source instead. And, in fact, the 'source' it gets given doesn't even need to be strictly legal Lisp at all: it can be something which the FEXPR knows how to manipulate to make something that is. That means you can, all of a sudden, extend the syntax of the language in pretty general ways. But the cost of being able to do that is that you can't compile any of this: the syntax you construct has to be interpreted at runtime, and the transformation happens each time the FEXPR is called.
Syntax transformers: macros
So, rather than use FEXPRs, you can do something else: you could change the way that evaluation works so that, before anything else happens, there is a stage during which the code is walked over and possibly transformed into some other code (simpler code, perhaps). And this need happen only once: once the code has been transformed, then the resulting thing can be stashed somewhere, and the transformation doesn't need to happen again. So the process now looks like this:
code is read in and structure built from it;
this initial structure is possibly transformed into other structure;
(the resulting structure is possibly compiled);
the resulting structure, or the result of compiling it is evaluated, probably many times.
So now the process of evaluation is divided into several 'times', which don't overlap (or don't overlap for a particular definition):
read time is when the initial structure is built;
macroexpansion time is when it is transformed;
compile time (which may not happen) is when the resulting thing is compiled;
evaluation time is when it is evaluated.
Well, compilers for all languages probably do something like this: before actually turning your source code into something that the machine understands they will do all sorts of source-to-source transformations. But these things are in the guts of the compiler and are operating on some representation of the source which is idiosyncratic to that compiler and not defined by the language.
Lisp opens this process to users. The language has two features which make this possible:
the structure that is created from source code once it has been read is defined by the language and the language has a rich set of tools for manipulating this structure;
the structure created is rather 'low commitment' or austere -- it does not particularly predispose you to any interpretation in many cases.
As an example of the second point, consider (in "my.file"): that's a function call of a function called in, right? Well, may be: (with-open-file (in "my.file") ...) almost certainly is not a function call, but binding in to a filehandle.
Because of these two features of the language (and in fact some others I won't go into) Lisp can do a wonderful thing: it can let users of the language write these syntax-transforming functions -- macros -- in portable Lisp.
The only thing that remains is to decide how these macros should be notated in source code. And the answer is the same way as functions are: when you define some macro m you use it just as (m ...) (some Lisps support more general things, such as CL's symbol macros. At macroexpansion time -- after the program is read but before it is (compiled and) run -- the system walks over the structure of the program looking for things which have macro definitions: when it finds them it calls the function corresponding to the macro with the source code specified by its arguments, and the macro returns some other chunk of source code, which gets walked in turn until there are no macros left (and yes, macros can expand to code involving other macros, and even to code involving themselves). Once this process is complete then the resulting code can be (compiled and) run.
So although macro look like function calls in the code, they are not just functions which don't evaluate their arguments, like FEXPRs were: instead they are functions which take a bit of Lisp source code and return another bit of Lisp source code: they're syntax transformers, or function which operate on source code (syntax) and return other source code. Macros run at macroexpansion time which is properly before evaluation time (see above).
So, in fact macros are functions, written in Lisp, and the functions they call evaluate their arguments perfectly conventionally: everything is perfectly ordinary. But the arguments to macros are programs (or the syntax of programs represented as Lisp objects of some kind) and their results are (the syntax of) other programs. Macros are functions at the meta-level, if you like. So a macro if a function which computes (parts of) programs: those programs may later themselves be run (perhaps much later, perhaps never) at which point the evaluation rules will be applied to them. But at the point a macro is called what it's dealing with is just the syntax of programs, not evaluating parts of that syntax.
So, I think your mental model is that macros are something like FEXPRs in which case the 'how does the argument get evaluated' question is an obvious thing to ask. But they're not: they're functions which compute programs, and they run properly before the program they compute is run.
Sorry this answer has been so long and rambling.
What happened to FEXPRs?
FEXPRs were always pretty problematic. For instance what should (apply f ...) do? Since f might be a FEXPR, but this can't generally be known until runtime it's quite hard to know what the right thing to do is.
So I think that two things happened:
in the cases where people really wanted normal order languages, they implemented those, and for those languages the evaluation rules dealt with the problems FEXPRs were trying to deal with;
in applicative order languages then if you want to not evaluate some argument you now do it by explicitly saying that using constructs such as delay to construct a 'promise' and force to force evaluation of a promise -- because the semantics of the languages improved it became possible to implement promises entirely in the language (CL does not have promises, but implementing them is essentially trivial).
Is the history I've described correct?
I don't know: I think it may be but it may also be a rational reconstruction. I certainly, in very old programs in very old Lisps, have seen FEXPRs being used the way I describe. I think Kent Pitman's paper, Special Forms in Lisp may have some of the history: I've read it in the past but had forgotten about it until just now.
A macro definition is a definition of a function that transforms code. The input for the macro function are the forms in the macro call. The return value of the macro function will be treated as code inserted where the macro form was. Clojure code is made of Clojure data structures (mostly lists, vectors, and maps).
In your foo macro, you define the macro function to return whatever blah did to your code. Since blah is (almost) the identity function, it just returns whatever was its input.
What is happening in your case is the following:
The string "(foo (+ 1 2 3))" is read, producing a nested list with two symbols and three integers: (foo (+ 1 2 3)).
The foo symbol is resolved to the macro foo.
The macro function foo is invoked with its argument xs bound to the list (+ 1 2 3).
The macro function (prints and then) calls the function blah with the list.
blah (prints and then) returns that list.
The macro function returns the list.
The macro is thus “expanded” to (+ 1 2 3).
The symbol + is resolved to the addition function.
The addition function is called with three arguments.
The addition function returns their sum.
If you wanted the macro foo to expand to a call to blah, you need to return such a form. Clojure provides a templating convenience syntax using backquote, so that you do not have to use list etc. to build the code:
(defmacro foo [xs]
`(blah ~xs))
which is like:
(defmacro foo [xs]
(list 'blah xs))
I would like to implement a naive non-lazy map in Java with a Java loop.
My main concern is function invocation in java from Clojure.
Here is my code :
A class called NaiveClojure to implement functions using Java
package java_utils;
import java_utils.ApplyFn;
public class NaiveClojure {
public static Object[] map (ApplyFn applyfn, Object function, Object[] coll) {
int len = coll.length;
for (int i = 0 ; i < len ; i++) {
coll[i] = applyfn.apply(function, coll[i]);
}
return coll;
}
}
An abstract class called ApplyFn
package java_utils;
public abstract class ApplyFn {
public abstract Object apply (Object function, Object value);
}
So in Clojure I have
(defn java-map [f coll]
(let [java-fn (proxy [ApplyFn] []
(apply [f x]
(f x)))]
(seq (NaiveClojure/map java-fn f (to-array coll)))))
I tried
(doall (map inc (range 0 10000))) ;; 3.4 seconds for 10000 operations
(java-map inc (range 0 10000) ;; 5.4 seconds
My point is not to outperform map (I implemented it as an example), I just want to do things like that with specific functions (not to reinvent the wheel of Clojure).
Is there a better way to pass functions like that ? (as an easy and faster way)
And to improve my coding in general (I have a poor theoritical knowledge), do you know what is killing perf here ?
I would say general typing like Object but I do not see anything else
Thanks
You have no cause for concern here, the way you are doing it is fine and efficient.
coll[i] = applyfn.apply(function, coll[i]);
This is a very normal way to go about this. When measuring it do please, as Valentin Waeselynck points out, remember to use a reliable microbenchmarking function and also keep in mind that benchmarking this kind of small code chunk in isolation is tricky.
When you generate a clojure function it produces a "normal" java class, with a method called apply. This will not be any slower to call because you are calling a function that was originally written in Clojure than it would be to call a method on a class that was written in the normal Java syntax. Once the Hotspot JIT finishes warming it up and inlining, it will likely be as fast as it would be without the method call (which is why benchmarking this kind of thing is harder than it intuitively should be).
I'm reading the Clojure Programming book. I'm at an example about partials and it go like this:
(def only-strings (partial filter string?))
The thing is, if the i write the next function:
(defn only-strings [x] (filter string? x))
I can have the same result:
user=> (only-strings [6 3 "hola" 45 54])
("hola")
What are the benefits of using a partial here? Or the example is just to simple to show them? Could somebody please give me an example where a partial would be useful. Many thanks.
The benefits of partial in this case is that you can fix the first argument and bind it to string?.
That's even all partial does. Predefining the first parameters as you can see in your and in Arthur's example.
(def foo (partial + 1 2))
(foo 3 4) ; same as (+ 1 2 3 4)
;=> 10
With partial i bound the first two arguments to 1 and 2 in this case.
Why could this be useful?
You may want to use map or apply on a function, which takes two arguments. This would be very bad, because map and apply take a function, which one needs one argument. So you might fix the first argument and use partial for this and you get a new function which only needs one argument. So it can be used with map or apply.
In one of my projects I had this case. I thought about using partial or an anonymous function. As I only needed it in one case, I used a lambda. But if you needed it more than one time, than defining a new function with partial would be very useful.
This eventually comes down to a matter of personal style, anything you do with partial you can do with an anonymous function, though sometimes partial makes it prettier. applying the first couple arguments to a variadic function is one example:
user> (def bigger+ (partial + 7 42))
#'user/bigger+
user> (bigger+ 1 2)
52
compared to:
user> (def bigger+ (fn [& nums] (apply + 7 42 nums)))
#'user/bigger+
user> (bigger+ 1 2)
52
Though of course you are free to prefer the second one if it looks better to you.
Here is an example:
(see the difference between DEFN and DEF)
(defn addDomain [domain user] ( str user domain))
(def buildEmail (partial addDomain "#domain.com"))
(buildEmail "info")
;; "info#domain.com"
If you want an example of how partial functions are useful, there's a real-world example that's very common in the Java world, where Java and Spring recreate partial function application (albeit in a clunky way).
Say you have a singleton component FooService that you configure in Spring, it's configured with the scope of singleton and has some stuff injected into it like a BarDao. The FooService has a bunch of business methods like retrieveBarsForSomeReason().
When the application starts up it reads the application context which instantiates the FooService and injects the BarDao into it as an instance variable. Later on the application calls methods on the FooService and the methods call on the BarDao as part of their work.
So this isn't a real object and there's nothing OO going on here, the methods on the service object are basically functions. Injecting state, in this example the BarDao, is equivalent to binding the object using partial so that you don't have to include it on later calls.
I was curious so I checked source code of swap! function on clojure repository, and it was like this:
(defn swap!
"Atomically swaps the value of atom to be:
(apply f current-value-of-atom args). Note that f may be called
multiple times, and thus should be free of side effects. Returns
the value that was swapped in."
{:added "1.0"
:static true}
([^clojure.lang.Atom atom f] (.swap atom f))
([^clojure.lang.Atom atom f x] (.swap atom f x))
([^clojure.lang.Atom atom f x y] (.swap atom f x y))
([^clojure.lang.Atom atom f x y & args] (.swap atom f x y args)))
And I don't know what the ".swap" function is doing? I tried to search for it but it's not defined in the same file, so can't find definition of it. Or is this another special thing that is actually not a function at all?
A lot of things in Clojure are actually implemented in Java, like reference types (atom, ref, var, agent), data structures (map, vector, list, set), namespaces (the actual Namespace class) and other stuff. When reading the source code for Clojure functions in clojure.core it's not rare to find an interop call to a Java method.
It is my understanding that there's a long term objective to implement these things in Clojure itself (search here for Clojure-in-Clojure), but for now these things are implemented in Java, which is really not so bad since the whole language is open source and you can check any implementation detail online in the github repo (already linked in a comment): Clojure (note that there's a jvm and a clj folder indicating in what language the code inside is implemented).
In Clojure, an expression (.x object a b c) results in a method call, which in Java would be expressed as object.x(a, b, c). For more details see Java Interop.
In this particular case, the swap! function calls an appropriately overloaded swap method of the clojure.lang.Atom instance passed as the first argument. The swap method contains the actual logic performing the swap.
Simply put, an atom is sth. that is under control of transactional memory. (Read about STM, please.) It is inmutable for its observers (dereferencing an atom returns inmutable state as of the instant of deref), but can be mutated transactionally. This is exactly what swap! does. It transactionally swaps the old value for the new value. Please note that it is very different from assignment. Assignment is not safe for concurrency.
In other words, atom works like a cell in a database table. When you query it, you will have a value, not an exception, even if at the same instant another query is updating it.
Cheers -