2009-06-28 67 views
3

當長度爲4時,循環執行5次。從流中讀取5個字符。Clojure循環讀取一個額外的


(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

在做read之前,您應該測試zero?。請注意,即使length == 0開頭,您的版本也會調用read

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

避免了另一種方式的明確loop

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

所以我應該在循環之前增加一個測試爲零,但我仍然不知道爲什麼它正在運行的5倍?這是clojure的行爲還是我錯過了什麼? – 2009-06-28 22:24:41

0

我不知道Clojure的,但在我看來像你在「結果」的形式再次讀取數據流,在CL這個喜歡最後?