11

bytes?次を返す関数をどのように記述しますか。

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

3 に答える 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 :)

于 2013-02-10T11:32:17.010 に答える
10
(defn bytes? [x]
  (if (nil? x)
    false
    (= (Class/forName "[B")
       (.getClass x))))

アップデート。同じ質問が既にここで尋ねられています オブジェクトが Clojure の Java プリミティブ配列であるかどうかをテストする. そして、Googleはあなたの質問に正確にそのページを提供します「clojureオブジェクトがバイト配列かどうかを確認する方法は?」;)

于 2013-02-10T11:27:52.527 に答える