I'm new to Clojure, and would appreciate feedback on this short program. The problem I set out to solve was selected at random from Project Euler, and is described in the comments. The part that I'm least happy about is the repeated series for the product, which I think could be replaced with a reduce call somehow.

; An irrational decimal fraction is created by concatenating the positive integers:
; 0.123456789101112131415161718192021...
;              ^
; It can be seen that the 12th digit of the fractional part is 1.
; If dn represents the nth digit of the fractional part, 
; find the value of the following expression:
;    d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000

(def d (apply str (map str (range 1 1000001)))) ; generate Champernowne's contant
(defn get-digit [x k] (read-string (.substring x k (+ k 1)))) ; get digit at position
(* (get-digit d 0)
   (get-digit d 9)
   (get-digit d 99)
   (get-digit d 999)
   (get-digit d 9999)
   (get-digit d 99999)
   (get-digit d 999999)
) ; product from problem statement

1 Answer 1


I'd simplify as follows:

(defn get-digit [x k] (Character/digit (.codePointAt x k) 10))
  • codePointAt is a method of Java's String class.
  • digit is a static method of Java's Character class.

Both of these are in Java.lang, hence included by default.

(->> 1
     (iterate (partial * 10))
     (map (comp (partial get-digit d) dec))
     (take 7)
     (apply *))

You can replace apply with reduce, if you prefer.

The calculation may be easier to follow as a series of bindings in a let form:

(let [powers-of-ten (iterate (partial * 10) 1)
      digits (map (comp (partial get-digit d) dec) powers-of-ten)
      seven-digits (take 7 digits)
      answer (apply * seven-digits)]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.