Skip to content

Instantly share code, notes, and snippets.

@scotthaleen
Created December 11, 2013 03:57
Show Gist options
  • Save scotthaleen/7904877 to your computer and use it in GitHub Desktop.
Save scotthaleen/7904877 to your computer and use it in GitHub Desktop.
CUSIP check digit -- http://en.wikipedia.org/wiki/CUSIP
(def lookup-int-val
(merge
{\* 36 \@ 37 \# 38}
(zipmap (map char(range 48 58)) (range))
(zipmap
(map char (range 65 91))
(drop 10 (range)))))
(defn inc-sum [sum v i]
(let [val (if (even? i) (* 2 v) v)]
(+ sum
(int (/ val 10))
(mod val 10))))
(defn compute-sum [cusip]
(loop [sum 0
i 1
xs (take 8 (clojure.string/upper-case cusip))]
(let [v (get lookup-int-val (first xs))]
(if (nil? v)
sum
(recur (inc-sum sum v i) (inc i) (rest xs))))))
(defn cusip-check-digit [cusip]
(mod (- 10 (mod (compute-sum cusip) 10)) 10))
;;(cusip-check-digit "912828NB2")
;;=>2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment