我陷入了 Clojure 循环,需要帮助才能摆脱。
我首先要定义一个向量
(def lawl [1 2 3 4 5])
我愿意
(get lawl 0)
并得到“1”作为返回。现在,我想要一个循环来获取向量中的每个数字,所以我这样做:
(loop [i 0]
(if (< i (count lawl))
(get lawl i)
(recur (inc i))))
在我看来,这应该将 i 的值设置为 nil,然后如果 i 小于 lawl 向量的计数,它应该获取每个 lawl 值,然后将 i 变量增加 1,然后再试一次,得到向量中的下一个值。
但是,这是行不通的,我花了一些时间试图让它工作,但完全卡住了,希望能得到一些帮助。我也尝试过将“if”更改为“when”并得到相同的结果,它不提供任何数据,REPL 只是进入一个新行并闪烁。
编辑:修复了复发。
最佳答案
您需要考虑“获取每个 lawl
值”的含义。您的 get
调用确实“获取”了适当的值,但是由于您从未对它做任何事情,所以它被简单地丢弃了; Bozhidar 关于添加 println
的建议是一个很好的建议,可以让您看到循环确实访问了 lawl
的所有元素(只需替换 (get . ..)
与 (println (get ...))
,修复 (inc)
=> (inc i)
Bozhidar 也提到过)。
就是说,如果您只想依次对每个数字做某事,loop
/recur
根本不是一个好方法。以下是其他一些:
;;; do some side-effecty thing to each number in turn:
(dotimes [i (count lawl)]
(println (str i ": " (lawl i)))) ; you don't really need the get either
;; doseq is more general than dotimes, but doesn't give you equally immediate
;; acess to the index
(doseq [n lawl]
(println n))
;;; transform the lawl vector somehow and return the result:
; produce a seq of the elements of lawl transformed by some function
(map inc lawl)
; or if you want the result to be a vector too...
(vec (map inc lawl))
; produce a seq of the even members of lawl multiplied by 3
(for [n lawl
:when (even? n)]
(* n 3))
这仅仅是个开始。要更好地了解 Clojure 的标准库,请参阅 Clojure -- Functional Programming for the JVM Mark Volkmann 的文章。
关于loops - 卡在 Clojure 循环中,需要一些指导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3222440/