Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

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.
question from:https://stackoverflow.com/questions/65903909/need-the-first-10-multiples-of-any-number-in-clojure

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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))))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...