Created
December 11, 2013 03:57
-
-
Save scotthaleen/7904877 to your computer and use it in GitHub Desktop.
CUSIP check digit -- http://en.wikipedia.org/wiki/CUSIP
This file contains 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
(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