On Mon, Feb 7, 2011 at 8:09 PM, Andreas Kostler
<andreas.koestler.le...@gmail.com> wrote:
> Hi all,
> Is it possible to read from a lazy input sequence? I have a telnet
> connection using commons.telnet and I want to do something like:
> (def telnet (TelnetClient.))
> (def in (. telnet getInputStream))
>
> ; How do I do this?
> (def read-until
>  ; read from a lazy input sequence UNTIL prompt is matched and return
> what's been read
>  [prompt input-stream]
> ...)
>
> Every idea is appreciated :)

Lazy seq of characters from input sequence:

(defn lazy-input
  "Returns a lazy sequence of characters from an input stream or Reader."
  [input-stream]
  (let [step (fn step []
               (let [c (.read input-stream)]
                 (when-not (== c -1)
                   (cons (char c) (lazy-seq (step))))))]
    (lazy-seq (step))))

Read up until a subseq:

(defn take-until-subseq
  "Searches forward through s until subseq or end of s.
   Returns s from start to just before first occurrence of subseq."
  [s subseq]
  (let [l (count subseq) ss (partition l 1 s) subseq (seq subseq)]
    (map first (take-while (fn [[_ x]] (not= x subseq)) (map vector s ss)))))

Read until a prompt from an input stream:

(defn read-until
  "Reads from an input stream or Reader until prompt."
  [prompt input-stream]
  (apply str (take-until-subseq (lazy-input input-stream) prompt)))

Test it:

user=> (read-until "baz" (java.io.StringReader. "foobarbazquux"))
"foobar"

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to