Clojure loop reads one extra

With a length of 4, the next cycle is performed 5 times. Reading 5 characters from the stream.


(loop [i (.read stream)  result ""  counter length]
    (let [c (char i)]
      (println "=>" c)
      (if (zero? counter)
        result
        (recur (.read stream) (str result c) (dec counter)))))
+3
source share
2 answers

You must check zero?before you do read. Please note that your version will call readonce, even if length== 0 to start.

(loop [result "" counter length]
  (if (zero? counter)
    result
    (let [c (char (.read stream))]
      (println "=>" c )
      (recur (str result c) (dec counter)))))

Another way to avoid the explicit loop:

(apply str 
       (take length 
             (repeatedly #(let [c (char (.read stream))]
                            (println "=>" c) c)))))
+3
source

I don’t know clojure, but it seems to me that you are reading the stream in the form of “result” again, is it like final in CL?

0
source

Source: https://habr.com/ru/post/1711450/


All Articles