Friday, 16 May 2014

Clojure practice - 2

After finishing the previous post I noticed that Kaloz's solution was a bit more concise, not leaning on a helper function. So here is a "more compact" version, even puttin the number->characters mapping definition in the same expression.

(defn compact-combinations [number]
  (let [num->chars { \2  "ABC" \3  "DEF" \4  "GHI" \5  "JKL" 
                    \6  "MNO" \7  "PQRS" \8  "TUV" \9  "WXYZ"}
        red-fn (fn [acc d]
                 (m/match (num->chars d)
                   nil acc
                   chs (for [c chs
                             i acc]
                           (str i c))))] 
    (reduce red-fn [""] number)))

(println (compact-combinations "34"))


or, purely for the sake of example, having even the println in it

(let [combinations (fn [number] 
                     (let [num->chars {\2  "ABC" \3  "DEF" \4  "GHI" \5  "JKL" 
                                       \6  "MNO" \7  "PQRS" \8  "TUV" \9  "WXYZ"}
                           red-fn (fn [acc d]
                                    (m/match (num->chars d)
                                      nil acc
                                      chs (for [c chs
                                                i acc]
                                              (str i c))))] 
                       (reduce red-fn [""] number)))]
  (println (combinations "514")))

No comments :

Post a Comment