2016-05-14 51 views
3

我發現它很難包圍我的頭。再說了,在Python,如果我想有我在基於用戶輸入一個循環修改名單,我有這樣的事情:類似Clojure的方式在一個循環中有一個數據結構

def do_something(): 
    x = [] 
    while(true): 
     input = raw_input('> ') 
     x.append(input) 
     print('You have inputted:') 
     for entry in x: 
      print(entry) 

我真的不知道什麼是Clojure中,最喜歡的方式做類似的事情。到目前爲止,我有這樣的事情:

(defn -main 
    [arg] 
    (print "> ") 
    (flush) 
    (let [input (read-string (read-line))] 
     ; Append a vector? 
     (println "You have inputted:") 
     ; Print the contents of vector? 
     (recur <the vector?>))) 

基本上,我追加載體,並給予載體作爲參數下一個遞歸循環。這是做這件事的正確方法嗎?我甚至不知道我會如何做到這一點,但我就是這麼做的。我將在哪裏「存儲」矢量?任何幫助?

回答

4

你在Python中做什麼是你正在變異向量x。這不是在clojure中做事的標準方式。 clojure中的數據結構默認是不可變的。因此,您必須每次創建新的向量並將其傳遞給下一次迭代。

(defn -main 
    [arg]  
    (loop [vec []] 
     (let [input (read-string (read-line))] 
     (let [next-vec (conj vec input)] 
      (println (str "You have inputted:" next-vec)) 
      (recur next-vec))))) 
0

這裏是它是如何工作的一個例子:

(ns clj.core 
    (:use tupelo.core)) 

(defn loopy [] 
;  "var" "init val" 
    (loop [ idx  0 
      result "" ] 
    (if (< idx 5) 
     (recur (inc idx)    ; next value of idx 
      (str result " " idx)) ; next value of result 
     result))) 
(spyx (loopy)) 


(defn -main []) 

和輸出:

> lein run 
(loopy) => " 0 1 2 3 4" 

所以loop表達式定義的環 「的變量」 和它們的初始值。 recur表達式爲循環的下一次迭代設置每個變量的值。

由於您正在積累用戶輸入,您可能需要使用字符串而不是矢量。或者,你可以像這樣改變它:

(defn loopy [] 
;  "var" "init val" 
    (loop [idx  0 
     result [] ] 
    (if (< idx 5) 
     (recur (inc idx)    ; next value of idx 
      (glue result [idx])) ; next value of result 
     result))) 
(spyx (loopy)) 


> lein run (loopy) => [0 1 2 3 4] 

將物品累積成矢量。請注意,您也可以在recur表達式中使用這種表達,而不是glue

(append result idx) 

其中函數appendglue,並spyx都是found in the Tupelo library。請享用!

相關問題