Skip to content

Instantly share code, notes, and snippets.

@javazquez
Last active March 19, 2018 02:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save javazquez/00319b7e412c72263867 to your computer and use it in GitHub Desktop.
Save javazquez/00319b7e412c72263867 to your computer and use it in GitHub Desktop.
Clojure Soundex
;;Example of Clojure Soundex Code for my blog
;;http://javazquez.com/juan/2012/08/28/clojure-soundex/
(def val-map {"FBVP" 1,"CGJKQSXZ" 2,"DT" 3,"L" 4,"MN" 5,"R" 6, "AEIOU" "!" }))
(defn map-builder [alphas num]
(zipmap alphas (repeat num)))
(def conversion-map
(reduce merge (map #(map-builder (key %) (val % )) val-map) ))
;;The non value '!' is critical for the dup removal since letters are counted twice if seperated by a vowel
(defn soundex-helper [word]
(->
(apply str (map conversion-map (.toUpperCase word ) ));map datatype will act as filter
(clojure.string/replace #"(?i)([\d])\1+" "$1" );replace dups
(subs 1 );remove first
(clojure.string/replace "!" "" );pull out non value
(str "000");pad with trailing 0s
(subs 0 3)))
(defn soundex [word]
(str (first word) (soundex-helper word)));
;; tests
(=(soundex "Ashcroft") "A261")
(=(soundex "Ashcraft") "A261")
(=(soundex "Tymczak") "T522")
(=(soundex "Pfister") "P236")
(=(soundex "Lukaskiewicz") "L222")
(=(soundex "Rubin") "R150")
(=(soundex "Rupert") "R163")
(=(soundex "Robert") "R163")
(=(soundex "Vazquez") "V220")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment