Search code examples
clojure

Need the first 10 multiples of any number in Clojure


We've been given a task to print the first ten multiples of any number for which we have written the below code. It is throwing an error. In simple words, if n is 2 then we need to create a table of 2's till 10.

(defn multiples [n]
       (while ( n < 11)    
          (println( n * n))       
     (swap! n inc)))
(def n (Integer/parseInt (clojure.string/trim (read-line))))
(multiples n)

With this, we're getting the error:

Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to clojure.lang.

Solution

  • Look at what iterate function does here

    (defn multiples-of [n]
      (iterate (partial * n) n))
    
    (def ten-multiples-of-ten
      (take 10 (multiples-of 10)))
    

    EDIT: I misread the author of the question, I believe he wants to just generate a sequence of squares. Here is one way using transducers, cause why not ;)

    (def xf
      (comp
        (map inc)
        (map #(* % %))))
    
    
    (defn first-n-squares [n]
      (into [] xf (take n (range))))