Clojure's thread does not show results in Emacs clojure-repl mode - emacs

I have this Clojure code that starts and executes a function.
(import [java.lang Thread])
(defn with-new-thread [f]
(.start (Thread. f)))
(with-new-thread (fn [] (print "hi")))
However, when I run it in emacs in slime-repl mode (executed with cider-jack-in, there is nothing printed out, but nil returned.
With lein real, I got the expected output.
user=> (import [java.lang Thread])
java.lang.Thread
user=> (defn with-new-thread [f] (.start (Thread. f)))
#'user/with-new-thread
user=> (with-new-thread (fn [] (print "hello\n")))
hello
nil
What might be wrong?

This happens because the main thread in CIDER/Emacs binds the REPL output buffer to the *out* dynamic var. This is why you can see things in emacs.
However when you start a new thread, that binding doesn't exist. Fixing is simple enough - first create a function which will capture the current binding:
(def repl-out *out*)
(defn prn-to-repl [& args]
(binding [*out* repl-out]
(apply prn args)))
Now, whenever you want to print from a different thread, use:
(prn-to-repl "hello")
And that's it. Hope this helps.

Related

Suppress output from print function in Lisp

I'm fairly new to Lisp, and I've run into a printing issue. I have one function which does printing to the standard output (among other things). I want to then run this function through another function where it still runs the same but instead nothing gets printed to the standard output.
Here is a simple example of what I mean. I have the following two functions described:
(defun does-printing()
(print "This goes to standard output."))
(defun run-other-function (function)
(funcall function)
(values))
Here's a dribble of what happens when I run this,
;; Dribble of #<IO TERMINAL-STREAM> started on 2014-10-05 21:49:49.
#<OUTPUT BUFFERED FILE-STREAM CHARACTER #P"example.out">
[7]> (run-other-function #'does-printing)
"This goes to standard output."
[8]> (dribble)
;; Dribble of #<IO TERMINAL-STREAM> finished on 2014-10-05 21:50:09.
Note that the printing function still prints to the standard output. It'd like to be able to suppress this printing somehow when running does-printing through run-other-function. I have tried many different variations of phrasing of my problem when searching for solutions, but nothing is getting at what I would like to do.
The simplest solution is to create an empty broadcast stream.
(with-open-stream (*standard-output* (make-broadcast-stream))
(call-some-function-1)
...
(call-some-function-n))
If a broadcast stream has no component stream all output will be discarded. Above binds the *standard-output* to such a stream. This does not cons up any data and it is portable.
You can just redirect your standard-output to some place. For example into /dev/null if you have one in your operating system. It looks like very idiomatic UNIX-way output suppressing.
Note, that you shouldn't set it to NIL, because print will signal type error in this case.
(defun does-printing()
(print "This goes to standard output."))
(defun run-other-function (function)
(with-open-file (*standard-output*
"/dev/null"
:direction :output
:if-exists :supersede)
(funcall function)
(values)))
CL-USER> (run-other-function #'does-printing)
; No value
Other option (and it may be better) is to use with-output-to-string, so you can capture this output value or just ignore it. Is think it's better, because why to do IO if we don't need it, and also it must work on any OS.
(defun run-other-function (function)
(with-output-to-string (*standard-output*
(make-array '(0)
:element-type 'base-char
:fill-pointer 0 :adjustable t))
(funcall function)
(values)))
If you doing it a lot, you can wrap it into macro or even function, to use in place of funcall.
(defun does-printing()
(print "This goes to standard output.")
"My result")
(defun funcall-with-no-output (fn)
(with-output-to-string (*standard-output*
(make-array '(0)
:element-type 'base-char
:fill-pointer 0 :adjustable t))
(funcall fn)))
CL-USER> (funcall-with-no-output #'does-printing)
"My result"
But i think macro will be more general and idiomatic for this case (may be I'm wrong).
(defmacro with-suppressed-output (&body body)
`(with-output-to-string (*standard-output*
(make-array '(0)
:element-type 'base-char
:fill-pointer 0 :adjustable t))
,#body))
So you can call many forms in with-suppressed-output.

confusing about Clojure macro definition

The clojure macro is a difficult point for me,
here is an macro example took from "Pratical Clojure":
(defmacro triple-do [form]
(list 'do form form form))
user=> (triple-do (println "test"))
test
test
test
nil
This triple-do works well
And I think the following version should work but not
(defmacro triple-do [form]
(do form form form))
user=> (triple-do (println "test"))
test
nil
why does it just print once?
and the following confuses me extremely
(defmacro test-macro [form] (do form (println "hard code test")))
user=> (test-macro (println "hello"))
hard code test
nil
why "hello" not show in console?
A macro is a function which returns a Clojure s-expression which is then compiled, or expanded again if the macro returns a macro. This process of replacement repeats recursivly until no macro's remain, then the final code is evaluated. It helps to think carefully about what runs while the macros are expanding compared to what the finally produced code will run.
The macroexpand-1 function can be really helpful by showing you what a macro expands:
user> (macroexpand-1 '(test-macro (println "hello")))
hard code test
nil
from this you can see that the print statement is happening while the macro is expanding. If you add a syntax quote before your do, the macro may make more sense.
user> (defmacro test-macro [form] `(do ~form (println "hard code test")))
#'user/test-macro
user> (macroexpand-1 '(test-macro (println "hello")))
(do (println "hello") (clojure.core/println "hard code test"))
In this case the print runs after the macro finishes expanding.
It will help to look at your examples through the lens of macroexpand, an essential tool for debugging macros.
Example 1:
(defmacro triple-do [form]
(list 'do form form form))
user=> (triple-do (println "test"))
Remember macros are supposed to return a list that will be executed at runtime. Let's see what this macro returns:
(macroexpand '(triple-do (println "test")))
;; (do (println "test") (println "test") (println "test"))
So it doesn't execute the code but rather returns a list that represents the code that will be executed once the macro is expanded. This is similar to trying the following snippet at the REPL:
(+ 1 2 3)
;; 6
(list '+ 1 2 3)
;; (+ 1 2 3)
With this in mind, let's turn to Example 2:
(defmacro triple-do [form]
(do form form form))
user=> (triple-do (println "test"))
Notice how the macro now doesn't return a list. It simply executes the do form which returns the last statement which is the form passed in. This can be easily seen by expanding the macro:
(macroexpand '(triple-do (println "test")))
;; (println "test")
That's why you end up with a single print statement.
This should give you a clue about Example 3:
(defmacro test-macro [form] (do form (println "hard code test")))
user=> (test-macro (println "hello"))
It's a bit trickier but let's expand it nevertheless:
(macroexpand '(test-macro (println "hello")))
;; hard code test <= this gets print before the macro fully expands
;; nil <= the expansion yields nil
Again, since you're not returning a list but rather simply executing a do form, it simply runs the println call from within the macro and since println returns nil, that becomes the result of the expansion.
To illustrate my point, this is how you'd have to rewrite your macro in order to achieve the desired behaviour:
(defmacro test-macro [form] (list 'do form (println "hard code test")))
(test-macro (println "hello"))
;; hard code test
;; hello
I hope this clears things for you.
Just remember this: macros are supposed to return lists that represent the code you'd like to be executed at runtime.
A macro must return, at compile time, the list that will take its place in the code.
Since do takes any number of arguments and returns the last, in each of your cases the macro expands to the last form in the do block.
The original returned a list with do as the first element, so rather than returning the last element in the block, it expanded to the whole block.

Dynamic scope in macros

Is there a clean way of implementing dynamic scope that will "reach" into macro calls? Perhaps more importantly, even if there is, should it be avoided?
Here's what I'm seeing in a REPL:
user> (def ^:dynamic *a* nil)
> #'user/*a*
user> (defn f-get-a [] *a*)
> #'user/f-get-a
user> (defmacro m-get-a [] *a*)
> #'user/m-get-a
user> (binding [*a* "boop"] (f-get-a))
> "boop"
user> (binding [*a* "boop"] (m-get-a))
> nil
This m-get-a macro isn't my actual goal, it's just a boiled down version of the problem I have been running into. It took me a while to realize, though, because I kept debugging with macroexpand, which makes everything seem fine:
user> (binding [*a* "boop"] (macroexpand '(m-get-a)))
> "boop"
Doing macroexpand-all (used from clojure.walk) on the outer binding call leads me to believe that the "issue" (or feature, as the case may be) is that (m-get-a) is getting evaluated before the dynamic binding takes:
user> (macroexpand-all '(binding [*a* "boop"] (f-get-a)))
> (let* []
(clojure.core/push-thread-bindings (clojure.core/hash-map #'*a* "boop"))
(try (f-get-a) (finally (clojure.core/pop-thread-bindings))))
user> (macroexpand-all '(binding [*a* "boop"] (m-get-a)))
> (let* []
(clojure.core/push-thread-bindings (clojure.core/hash-map #'*a* "boop"))
(try nil (finally (clojure.core/pop-thread-bindings))))
Here's my crack at a workaround:
(defmacro macro-binding
[binding-vec expr]
(let [binding-map (reduce (fn [m [symb value]]
(assoc m (resolve symb) value))
{}
(partition 2 binding-vec))]
(push-thread-bindings binding-map)
(try (macroexpand expr)
(finally (pop-thread-bindings)))))
It will evaluate a single macro expression with the relevant dynamic bindings. But I don't like using macroexpand in a macro, that just seems wrong. It also seems wrong to resolve symbols in a macro--it feels like a half-assed eval.
Ultimately, I'm writing a relatively lightweight interpreter for a "language" called qgame, and I'd like the ability to define some dynamic rendering function outside of the context of the interpreter execution stuff. The rendering function can perform some visualization of sequential instruction calls and intermediate states. I was using macros to handle the interpreter execution stuff. As of now, I've actually switched to using no macros at all, and also I have the renderer function as an argument to my execution function. It honestly seems way simpler that way, anyways.
But I'm still curious. Is this an intended feature of Clojure, that macros don't have access to dynamic bindings? Is it possible to work around it anyways (without resorting to dark magic)? What are the risks of doing so?
Macro expansion take place during the compilation of you program, so it's imposisble to predict the future value of dynamic variable at that time.
But, probably, you don't need to evaluate *a* during macro expansion and just wants to leave it as is. It this case *a* will be evaluated when the actual code is called. In this case you should quote it with ` symbol:
(defmacro m-get-a [] `*a*)
Your implementation of m-get-a causes clojure to replace (m-get-a) with its value when the code is compiled, which is the core binding of *a*, while my wersion causes it to replace (m-get-a) with variable *a* itself.
You need to quote *a* to make it work:
user=> (def ^:dynamic *a* nil)
#'user/*a*
user=> (defmacro m-get-a [] `*a*)
#'user/m-get-a
user=> (binding [*a* "boop"] (m-get-a))
"boop"

Clojure How to Expand Macro in Source File Versus Repl

I am leaning macros in Clojure and have a question about macro expansion. In the repl, when I do this:
user=> (defmacro unless [pred a b] `(if (not ~pred) ~a ~b))
#'user/unless
user=> (macroexpand-1 '(unless (> 5 3) :foo :bar))
(if (clojure.core/not (> 5 3)) :foo :bar)
But when I do the same in a clj file:
(ns scratch-pad.core
(:gen-class))
(defmacro unless [pred a b]
`(if (not ~pred) ~a ~b))
(defn -main [& args]
(prn
(macroexpand-1 '(unless (> 5 3) :foo :bar))))
and run the code, I get this:
$ lein run
(unless (> 5 3) :foo :bar)
How do I get the code to print the same as the repl?
What's going on
This happens because of how the notion of the current namespace works in Clojure. macroexpand-1 expands its argument in the current namespace.
At the REPL, this will be user; you're defining the macro in the user namespace, then you call macroexpand-1 in that namespace and all is good.
In a :gen-class'd namespace, or indeed any other namespace, the compilation-time current namespace is that namespace itself. When you later call the code defined in this namespace, however, the then-current namespace will be whatever is appropriate at that point. That might be some other namespace as it gets compiled.
Finally, at your app's runtime, the default current namespace is user.
To see this, you could move the macro to a separate namespace also defining a function use-the-macro and calling this function at top level; the :gen-class'd namespace would then need to require or use the macro's namespace. Then lein run will print what you expect once (at the macro's namespace's compilation time) and the unexpanded form twice (when the macro's namespace is required by the main namespace and then when -main calls use-the-macro).
Solutions
The Clojure REPL controls the current namespace using binding; you can do the same:
(binding [*ns* (the-ns 'scratchpad.core)]
(prn (macroexpand-1 ...)))
You can also use syntax-quote instead of quote in -main:
(defn -main [& args]
(prn (macroexpand-1 `...)))
^- changed this
Of course if symbols other than unless were involved, you'd have to decide whether they should be namespace-qualified in the output and possibly prefix them with ~'. This is the point though -- syntax-quote is good for producing mostly "namespace-independent" code (which is what makes it so great for writing macros, besides the convenient syntax).
Another possible "fix" (tested on Clojure 1.5.1) is adding an in-ns call to -main:
(defn -main [& args]
(in-ns 'scratchpad.core)
(prn (macroexpand-1 '...)))
^- no change here this time
As with binding, this way you're actually getting the expansion of your original form in your original namespace.

Clojure macro that builds a higher order function from a function

I'm trying to write a macro that builds middleware akin to that used in compojure.
I want to be able to call:
(def-middleware plus-two [x]
(+ 2 x))
And have the result look like:
(defn plus-two [f]
(fn [x]
(f (+ 2 x)))
I've got this far from reading on-line guides but it's not working out for me:
(defmacro def-middleware [fn-name args & body]
'(defn ~fn-name [f]
(fn ~args
(f ~#body))))
Any help or a pointer to a better macro writing guide would be great, thanks.
Let's see what macroexpand-1 gives us:
user=> (clojure.pprint/pprint (macroexpand-1 '(def-middleware plus-two [x] (+ 2 x))))
(defn
~fn-name
[f]
$
(fn ~args$ (f (clojure.core/unquote-splicing body))))
Not precisely what we're after! First things first: if you want to unquote things in a macro, you need to use "`" (the quasiquote/syntax-quote operator), not "'". Also, I'm not sure what you're after with those dollar signs, but it might be that you're going for the clojure's handy shortcut for using gensym for hygiene. But you need it immediately after each identifier you use it with (so [f#], not [f]$), and you need it on each occurrence of the identifier. And you don't need it with args. Putting all this together:
user=> (defmacro def-middleware [fn-name args & body] `(defn ~fn-name [f#] (fn ~args (f# ~#body))))
#'user/def-middleware
user=> (clojure.pprint/pprint (macroexpand-1 '(def-middleware plus-two [x] (+ 2 x))))
(clojure.core/defn
plus-two
[f__594__auto__]
(clojure.core/fn [x] (f__594__auto__ (+ 2 x))))
nil
user=>
Perhaps this is just a macro exercise, but the specific example of defining a middleware function is not good - you lose a lot of the flexibility that the middleware concept gives you. For example, why should this evaluate (f (+ 2 x)) instead of (+ 2 (f x))? Both are sensible ways to wrap this function, and your syntax gives no way to describe the latter. Really just defining a function-returning-function is flexible, simple, and easy; this macro brings little to the table.