Search code examples
clojureprimitive

Detecting whether a Clojure expression is primitive


Is it possible to detect in some way whether a Clojure expression is guaranteed to be primitive?

e.g. I'd like a macro that could do this

(is-primitive-expression? (+ 1.0 2.0))
=> true

(is-primitive-expression? (+ 1N 2.0))
=> false

Solution

  • I'm not sure I quite understand what a primitive expression is (still reading up on it). However, I found a function from clojure.contrib.repl-utils called expression-info, that claims to return information about whether the expression is primitive or not.

    See here: http://clojuredocs.org/clojure_contrib/clojure.contrib.repl-utils/expression-info

    I simply copied the source code and tried it out, but discovered I needed to do this import first:

    (import '(clojure.lang RT Compiler Compiler$C))
    

    However, I tried it out with your examples, but it returned true for both (I tried quoted and unquoted expressions because I could not tell which one it required):

    => (expression-info (+ 1N 2.0))
    => {:class double, :primitive? true} 
    => (expression-info (+ 1.0 2.0))
    => {:class double, :primitive? true}
    => (expression-info '(+ 1.0 2.0))
    => {:class double, :primitive? true}
    => (expression-info '(+ 1N 2.0))
    => {:class double, :primitive? true}
    

    Maybe some of this could provide you with useful clues/hints, but this may be very unhelpful seeing as I don't really understand what you are asking (yet).