我刚刚进入Clojure并且希望做一些简单的功能让我的脚湿透,并试图摆脱我的Imperative编程背景。
下面简单地在字符串中搜索重复元素,但是循环似乎将其旋转失控;我做错了什么?是的,这可能看起来势在必行;我仍然试图围绕功能编程和非状态变化。是的,html没有经过验证,我只是以它为例。
(def src "
<html>
<head>
<title>Astronomy
</title>
<title>Science
</title>
</head>
</html>
")
(defn findit [ele body i]
(let [n (.indexOf body (clojure.string/join ["<" ele ">"]) i)]
(if (> n -1)
(let [n2 (.indexOf body (clojure.string/join ["</" ele ">"]) (+ n 1))] ;if we found opening element, then find closing element
(if (> n2 -1) ;found both open and close of element?
[(subs body (+ n (.length ele) 2) n2) (+ n2 1)]))))
)
; (let [[r i] (findit "title" src 69)] (println i) (if r (println r,i)))
(defn findthem [ele body]
(loop [x 0]
(let [[r i] (findit ele body 0)]
(println r,i)
(if i
(recur i)))
)
)
(findthem "title" src)
答案 0 :(得分:2)
在循环的每次迭代中发生的let
语句中,调用findit
时索引为0
,而不是x
(或i
})。
(defn findthem [ele body]
(loop [i 0]
(let [[r i] (findit ele body i)]
(println r i)
(when i
(recur i)))))