From googling around, I found that using while loops or using variables is discouraged.
Now I implemented a very simple algorithm that will read characters from an inputstream and parse accordingly: if input is 10:abcdefghej it will parse out 10 then read next 10 bytes after the colon.
The thing I am kinda lost with is how I can refactor this so it does not rely on variables.
(defn decode-string [input-stream indicator]
(with-local-vars [length (str (char indicator) )
delimiter (.read input-stream )
string (str "")
counter 0 ]
(while (not(= (var-get delimiter) 58 ))
(var-set length (str (var-get length) (char (var-get delimiter)) ))
(var-set delimiter (.read input-stream )))
(var-set length (new BigInteger (var-get length)) )
(var-set counter (var-get length))
(while (not(zero? (var-get counter) ))
(var-set string (str (var-get string) (char (.read input-stream )) ))
(var-set counter (dec (var-get counter))))
(var-get string)))
Also, I understand that the only way to declare variables is using the with-local-vars keyword. Isn’t it kind of unpractical to define all the variables in one block at the beginning, or am I missing some crucial point?
A bit late to this party, I suppose, but the problem is much simpler if you just treat the string as a sequence of characters and use Clojure’s sequence-handling primitives:
A summary:
beforeandafter, and strip out the:while we are at it, by binding it to an unused local, namedcolonfor descriptiveness.beforeto get its numerical valueafter, and mash them all together into a string with(apply str)Svante’s answer is an excellent example of how to write loop-ish code with Clojure; I hope that mine is a good example of assembling the built-in functions so that they do what you need. Certainly both of these make the C solution look anything but “very simple”!