12

How would one write the function bytes? that returns the following:

(bytes? [1 2 3]) ;; => false
(bytes? (byte-array 8)) ;; => true

3 Answers 3

12

The way I used to do this until now was creating an array of that type and testing for it's class. To prevent creating an unnecessary instance every time, make a function that closes over the class of that particular array type.

(defn test-array
  [t]
  (let [check (type (t []))]
    (fn [arg] (instance? check arg))))

(def byte-array?
  (test-array byte-array))

=> (byte-array? (byte-array 8))
true

=> (byte-array? [1 2 3])
false

Mobyte's example seems a lot simpler though, and it seems I'll have some refactoring to do where I used this :)

Sign up to request clarification or add additional context in comments.

2 Comments

No answer is entitled to upvotes: people like what they like. In my experience, complaining about lack of votes discourages them still more.
@NielsK I've upvoted your answer. Not because of your solicitation though, but because it's better :-).
11
(defn bytes? [x]
  (if (nil? x)
    false
    (= (Class/forName "[B")
       (.getClass x))))

Update. The same question has been already asked here Testing whether an object is a Java primitive array in Clojure. And google gives exactly that page on your question "how to check if a clojure object is a byte-array?" ;)

2 Comments

The 'forName' part is very inefficient and implementation-dependent. Nielsk's answer is faster and more robust.
@dimagog is right. Instead of editing the code I would just like to note that (Class/forName "[B") can be moved into a var like (def ^{:private true} bytes-class (Class/forName "[B")). This was you pay var dereferencing cost instead of reflection cost at runtime. I don't know which one is worse. Also AFAIK ^:const doesn't work in this case.
6

Clojure.core version 1.9 onwards supports a bytes? function. Here's the Clojuredocs link

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.