陷入Clojure循环,需要一些指导

ble*_*fly 4 lisp loops if-statement clojure

我陷入了Clojure循环,需要帮助才能离开.

我首先要定义一个向量

(def lawl [1 2 3 4 5])
Run Code Online (Sandbox Code Playgroud)

我做

(get lawl 0)
Run Code Online (Sandbox Code Playgroud)

得到"1"作为回报.现在,我想要一个循环来获取向量中的每个数字,所以我这样做:

(loop [i 0]
   (if (< i (count lawl)) 
     (get lawl i) 
       (recur (inc i))))
Run Code Online (Sandbox Code Playgroud)

在我看来,这应该将i的值设置为nil,然后如果i低于lawl向量的计数,它应该得到每个lawl值然后用i增加i变量并再次尝试,得到下一个值在向量中.

然而,这不起作用,我花了一些时间试图让它工作,并完全卡住,将感谢一些帮助.我也尝试将"if"改为"when",结果相同,它没有提供任何数据,REPL只是输入一个新行并闪烁.

编辑:修复了复发.

Mic*_*zyk 7

你需要考虑什么是"获得每个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))
Run Code Online (Sandbox Code Playgroud)

这仅仅是个开始.有关Clojure标准库的详细介绍,请参阅Mark Volkmann撰写的Clojure - JVM功能编程文章.