Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if a clojure object is a byte-array?

Tags:

clojure

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

(bytes? [1 2 3]) ;; => false
(bytes? (byte-array 8)) ;; => true
like image 713
zcaudate Avatar asked Feb 10 '13 10:02

zcaudate


3 Answers

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 :)

like image 184
NielsK Avatar answered Oct 14 '22 07:10

NielsK


(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?" ;)

like image 35
mobyte Avatar answered Oct 14 '22 08:10

mobyte


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

like image 33
shark8me Avatar answered Oct 14 '22 06:10

shark8me