类似Clojure的在循环中拥有数据结构的方法
我觉得这件事让我很难理解。比如说,在Python中,如果我想有一个列表,并根据用户输入在循环中修改,我会有如下内容:类似Clojure的在循环中拥有数据结构的方法,clojure,Clojure,我觉得这件事让我很难理解。比如说,在Python中,如果我想有一个列表,并根据用户输入在循环中修改,我会有如下内容: def do_something(): x = [] while(true): input = raw_input('> ') x.append(input) print('You have inputted:') for entry in x: print(entry)
def do_something():
x = []
while(true):
input = raw_input('> ')
x.append(input)
print('You have inputted:')
for entry in x:
print(entry)
(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?>)))
(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]
我真的不确定做类似事情最像Clojure的方式是什么。到目前为止,我有这样的想法:
def do_something():
x = []
while(true):
input = raw_input('> ')
x.append(input)
print('You have inputted:')
for entry in x:
print(entry)
(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?>)))
(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]
(defn-main
[arg]
(打印“>”)
(齐平)
(让[输入(读取字符串(读取行))]
附加向量?
(println“您已输入:”)
;打印向量的内容?
(再次出现)
基本上,我附加向量,并将向量作为下一个递归循环的参数。这是正确的做法吗?我甚至不知道我会怎么做,但我会这么做。我将在哪里“存储”向量?有什么帮助吗?您在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)))))
以下是它的工作原理示例:
(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 [] )
因此,loop
表达式定义了循环“变量”及其初始值。recur
表达式为循环的下一次迭代设置每个变量的值
由于您正在累积用户输入,因此可能希望使用字符串而不是向量。或者,您可以这样更改它:
def do_something():
x = []
while(true):
input = raw_input('> ')
x.append(input)
print('You have inputted:')
for entry in x:
print(entry)
(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?>)))
(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]
其中,append
、glue
和spyx
都是函数。享受吧