我觉得这很难缠住我的头。假设,在Python中,如果我想有一个基于用户输入在循环中修改的列表,则将有类似以下内容:
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?>)))
基本上,我附加向量并将向量作为下一个递归循环的参数。这是正确的方法吗?我什至不知道我该怎么做,但这就是我要怎么做。我将在哪里“存储”向量?有什么帮助吗?
您在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)))))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句