简体   繁体   中英

clojure macro create || comparison?

I want to create an || comparison with Clojure like other languages.

(defmacro ||
  [source & other]
  `(loop [s# [~source ~@other]]
     (println s#)
     (let [fs# (first s#)]
       (if fs#
         fs#
         (if (= (count s#) 1)
           fs#
           (recur (next s#)))))))

but this can't work. fs# value is quote data.

like this

(def a [1])
(defn b []
  (println 11111))

(|| (get a 0) (b))

I want the result to be 1, this is (get a 0) but the result is (get a 0) this is Expression, not a var. How do I create an || macro?

Clojure's equivalent of || is the macro or . You can view its implementation here .

If you want to use the symbol || , you can just alias the or macro:

(def #^{:macro true} || #'or)

You can then use either:

(or (get a 0) (b))

or

(|| (get a 0) (b))

What's your expected result, (get a 0) or 1 ? On my machine ,the result of your code is 1 . I think that's nothing to do with macros. Before expanding the macro (|| (get a 0) (b)) , (get a 0) and (b) will be evaluated and the macro just get arguments 1 and nil . If you want result of (get a 0) , you should use (|| '(get a 0) (b))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM