views:

1381

answers:

2
+4  Q: 

Clojure While Loop

I trying clojure i am trying to figure out how to implement the following algorithm,

I am reading from an input stream i want to continue reading until it is not a delimiter character.

i can do this in java with a while loop but i can't seem to figure out how to do it in clojure?

while
   read
   readChar != delimiter

   do some processing....
end while
+5  A: 

I don't know Clojure, but it looks that, like Scheme, it supports "let loops":

(loop [char (readChar)]
   (if (= char delimiter)
       '()
       (do (some-processing)
           (recur (readChar)))))

Hope this is enough to get you started. I referred to http://clojure.org/special_forms#toc9 to answer this question.

NOTE: I know that Clojure discourages side-effects, so presumably you want to return something useful instead of '().

Nathan Sanders
+3  A: 

I came up with this in the spirit of line-seq. It's fully lazy and exhibits more of Clojure's functional nature than loop.

(defn delim-seq
  ([#^java.io.Reader rdr #^Character delim]
     (delim-seq rdr delim (StringBuilder.)))
  ([#^java.io.Reader rdr #^Character delim #^StringBuilder buf]
     (lazy-seq
       (let [ch (.read rdr)]
         (when-not (= ch -1)
           (if (= (char ch) delim)
             (cons (str buf) (delim-seq rdr delim))
             (delim-seq rdr delim (doto buf (.append (char ch))))))))))

Full paste.

Drew R.
Gotta be a shorter way 'ta do this.
Tchalvak