2011-01-31 12 views

Odpowiedz

14

Wyjazd with-in-str:

http://clojure.github.com/clojure/clojure.core-api.html#clojure.core/with-in-str

ClojureDocs ma przykład użycia:

;; Given you have a function that will read from *in* 
(defn prompt [question] 
    (println question) 
    (read-line)) 

user=> (prompt "How old are you?") 
How old are you? 
34     ; <== This is what you enter 
"34"     ; <== This is returned by the function 

;; You can now simulate entering your age at the prompt by using with-in-str 

user=> (with-in-str "34" (prompt "How old are you?")) 
How old are you? 
"34"     ; <== The function now returns immediately 
+0

Dzięki. To jest właściwa odpowiedź na to pytanie, ale to, czego naprawdę potrzebowałem, było trochę inne. Zobacz odpowiedź poniżej. – zippy

+0

Czy możesz dodać również przykład, ponieważ podany link też go nie ma. –

+0

Clojuredocs ma przykład: http://clojuredocs.org/clojure_core/clojure.core/with-in-str – sanityinc

3

Oto przykładowy kod dla tego, co skończyło się robi. Ideą jest prosta funkcja pętli do odczytu/drukowania na serwerze, która pobiera strumień wejściowy i wyjściowy. Mój problem polegał na tym, jak generować strumienie testowe dla takiej funkcji, i pomyślałem, że funkcja string mogłaby to zrobić. Zamiast tego jest to potrzebne:

(ns test 
    (:use [clojure.java.io :only [reader writer]])) 
(def prompt ">") 
(defn test-client [in out] 
    (binding [*in* (reader in) 
      *out* (writer out)] 
      (print prompt) (flush) 

(loop [input (read-line)] 
      (when input 
       (println (str "OUT:" input)) 
       (print prompt) (flush) 
       (if (not= input "exit\n") (recur (read-line))) 
       )))) 
(def client-stream (java.io.PipedWriter.)) 
(def r (java.io.BufferedReader. (java.io.PipedReader. client-stream))) 
(doto (Thread. #(do (test-client r *out*))) .start) 

(.write client-stream "test\n") 
Powiązane problemy