0
votes

I'm working through the 4clojure problems. I came across this answer for #120, which I would have totally never thought of on my own:

 (fn sum-square [coll]
  (let [digits (fn [n] (map #(- (int %) 48) (str n)))
    square #(* % %)
    sum-digits (fn [n] (reduce + (map square (digits n))))]
(count (filter #(< % (sum-digits %)) coll))))

The part I'm really trying to understand is how the digits part of it works.

(fn [n] (map #(- (int %) 48) (str n))

I'm really confused about how

(map #(- (int %) 48) "10")

returns

(1 0)

Can you please explain how this works? I'm confused about why n has to be turned into a string, and why it's then turned back into an integer, and why it has 48 subtracted. I'm sure there must be some really neat trick I'm missing.

Thanks!

1

1 Answers

7
votes

"10" in the context of map can be treated as a seq of chars(in this case \1 and \0) then int converts say \1 to ascii 49, and \0 to ascii 48 then - 48 converts 49 to 1 and 48 to 0