Created
May 21, 2025 02:43
-
-
Save jamesdavidson/a0877f3a81ff2e9315e00bb26f2f72e0 to your computer and use it in GitHub Desktop.
Fast cardinality of C# BitArray from Clojure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; Fast cardinality of C# BitArray from Clojure because for some reason BitArray lacks this (see java.util.BitSet) | |
(import '[System.Collections BitArray] '[System.Reflection BindingFlags FieldInfo]) | |
(def field-info (-> BitArray (.GetField "m_array" (enum-or BindingFlags/NonPublic BindingFlags/Instance)))) | |
(defn get-cardinality | |
[^BitArray ba] | |
(let [array (.GetValue ^FieldInfo field ba) | |
n (count array)] | |
(loop [i 0 acc 0] | |
(if (< i n) | |
(recur (unchecked-inc i) (unchecked-add-int acc (Int32/PopCount (aget ^ints array i)))) | |
acc)))) | |
(comment | |
(def t (doto (new BitArray 1000) (.Set 500 true) (.Set 600 true))) | |
(count (filter true? t)) ;; 2 | |
(get-cardinality t) ;; 2 | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment