0

我刚刚进入 Clojure,想做一些简单的函数来弄湿我的脚,并尝试摆脱我的命令式编程背景。

下面只是简单地搜索一个字符串中的重复元素,但是循环似乎使它失去了控制;我做错了什么?是的,这可能看起来势在必行;我仍在尝试围绕函数式编程和非状态更改。是的,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)
4

1 回答 1

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)))))
于 2013-03-18T15:35:15.347 回答