Skip to content

Instantly share code, notes, and snippets.

@ponzao
Last active December 20, 2015 07:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ponzao/6095989 to your computer and use it in GitHub Desktop.
Save ponzao/6095989 to your computer and use it in GitHub Desktop.
Martin Odersky's Phone Coder example translated into Clojure
(use '[clojure.string :only (join)])
(defn coder
[dictionary]
(let [mnemonics {\2 "ABC" \3 "DEF" \4 "GHI" \5 "JKL",
\6 "MNO" \7 "PQRS" \8 "TUV" \9 "WXYZ"}
char-code (into {} (mapcat (fn [[n cs]]
(map #(vector % n) cs))
mnemonics))
word-code (fn [word]
(join (map char-code (.toUpperCase word))))
words-for-number (group-by word-code dictionary)
encode (fn encode [number]
(if (empty? number)
#{()}
(set (for [split (range 1 (inc (count number)))
word (words-for-number (join (take split number)))
xs (encode (join (drop split number)))]
(cons word xs)))))]
(fn [number]
(map (partial join " ") (encode number)))))
(def dictionary
(set (with-open [rdr (clojure.java.io/reader "/usr/share/dict/words")]
(doall (filter #(re-matches #"[a-zA-Z]+" %)
(filter #(> (count %) 1) (line-seq rdr)))))))
(def translate
(coder (conj dictionary "Scala" "rocks")))
(translate "7225276257")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment