gpt4 book ai didi

类似 Clojure 的方式在循环中使用数据结构

转载 作者:行者123 更新时间:2023-12-02 16:51:53 27 4
gpt4 key购买 nike

我发现很难理解这一点。比如说,在 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)))))

关于类似 Clojure 的方式在循环中使用数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37231016/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com