0
votes

I need when-not-empty-let macro similar to clojure/core's when-let. So, I've just added not-empty call to when-let macro from clojure's source code:

(defmacro when-not-empty-let
  "bindings => binding-form test
  When test is not empty, evaluates body with binding-form bound to the value of test"
  [bindings & body]
  (.log js/console "check")
  (let [form (first bindings) tst (second bindings)]
    `(let [temp# ~tst]
       (when (not-empty temp#)
         (let [~form temp#]
           ~@body)))))

(also replaced (bindings 0) with (first bindings) as it didn't compile otherwise)

I use it in a following way:

(defn something
  []
  (when-not-empty-let [foo ["foo"]]
    (.log js/console foo)))

(something)

I'm getting following output:

undefined

check

What am I doing wrong?


Builded with Clojure v1.9.0, ClojureScript: v1.10.126, lein-cljsbuild: v1.1.7

Tested in Chrome v59.0.3071.115 under Ubuntu.


UPD: jsbin that reproduces issue (at least for me): https://jsbin.com/liluwer/1/edit?js,output

See output from question in browser's developer tool console.

1
Cannot reproduce, at least using Clojure. I doubt a difference in Cljs behavior would cause this though. Your output also doesn't seem to make sense. "check" should happen immediately, and undefined should happen after that. If you're getting nothing after "check" it would appear the undefined is unrelated, and you're actually getting no output at all. Running this in Clojure (after changing the prints to println, I get as outout check [foo] (with a newline between them). - Carcigenicate
The binding assignments can also be reduced down to (let [[form tst] bindings] using deconstruction. Not the problem here, but it's a lot nicer looking. - Carcigenicate
@Carcigenicate thanks for your participation, I've updated question with link to jsbin, pls check it out. - Glen Swift
I'm not sure what's going on with the jsbin. "Output" just shows a pixel value, and "console" shows the expanded macro for some reason, but not the run code. - Carcigenicate
@Carcigenicate That's the best fiddler I've found so far, unfortunately you should open browser dev tool to see actual logs (that's usually F12 / console section) - Glen Swift

1 Answers

1
votes

From ClojureScript docs:

There is a strict rule for when you can use defmacro -- you can only use it in what we call a macro namespace, effectively forcing you to separate your compile time and runtime code.

The error is I tried to test the macro in the same namespace.