String 想要更多的Clojure方式来强制字符串匹配吗
我在Clojure中实现了一个蛮力字符串匹配算法。它可以正常工作,但我要寻找的是如何使代码“更干净”,更具可读性。请注意,我还必须让算法打印出它是如何进行字符比较的。我不知道所有需要注意的约定,我真的很想知道如何更好地编写Clojure的一些技巧 它的作用:它获取一段文本,并且对于它的每个索引(因为文本是字符串类型),将其与输入字符串匹配。如果有匹配项,我们将第二个字符与文本的下一个索引进行比较。用英语解释有很多,但是如果你运行这个程序,它会打印出它在做什么 守则:String 想要更多的Clojure方式来强制字符串匹配吗,string,clojure,match,String,Clojure,Match,我在Clojure中实现了一个蛮力字符串匹配算法。它可以正常工作,但我要寻找的是如何使代码“更干净”,更具可读性。请注意,我还必须让算法打印出它是如何进行字符比较的。我不知道所有需要注意的约定,我真的很想知道如何更好地编写Clojure的一些技巧 它的作用:它获取一段文本,并且对于它的每个索引(因为文本是字符串类型),将其与输入字符串匹配。如果有匹配项,我们将第二个字符与文本的下一个索引进行比较。用英语解释有很多,但是如果你运行这个程序,它会打印出它在做什么 守则: (defn undersco
(defn underscores [n]
(apply str (repeat n "_")))
(defn brute_force_string_match
"Receives text as string type as its first argument,
string in second argument, brute force matches the
string to the text. Assumes text is longer than string."
[text
string]
;; for loop
;; i is 1 less than the amount of No matches you will get
(loop [i 0
j_and_matches [0 0]]
;;outer loop stops when i > n -m
(if (and
(<= i (- (count text) (count string)))
(not= (j_and_matches 0) (count string)))
;; the "while loop"
(do
(println "")
(print "\nPos = " i "\n"text"\n"
(str (underscores i) string))
(recur
(inc i)
(loop [j 0
print_pos i
undscore_amt 0
matches (j_and_matches 1)]
(if (and
(< j (count string))
(= (.charAt string j) (.charAt text (+ i j))))
(do
(print "\n" (str (str (underscores print_pos)) "^ Match! "))
(recur (inc j)
(inc print_pos)
(inc undscore_amt)
(inc matches)))
(do
(if (not= j (count string))
(print "\n" (str (str (underscores print_pos)) "^ No Match ")))
[j matches])))))
(if (= (j_and_matches 0) (count string))
(do (println "\n Pattern found at position " (dec i))
(println "The number of comparisons: " (+ (j_and_matches 1) (dec i)))
(dec i))
-1))))
(defn下划线[n]
(应用str(重复n“”))
(定义蛮力字符串匹配)
“以字符串类型接收文本作为其第一个参数,
字符串在第二个参数中,蛮力匹配
字符串。假定文本比字符串长。“
[正文]
字符串]
循环
我比你得到的不匹配的数量少1
(循环[i 0
j_和_匹配[0]]
当i>n-m时,外部循环停止
(如有)(及
(首先,j
在您的外循环中没有位置,它让i
遍历可能的匹配起点。j
是string
的本地索引,同时根据从i
开始的文本对其进行测试
我会这样写:
(defn brute_force_string_match [text string]
(let [last-start (- (count text) (count string))]
(loop [i 0, matches []]
(if (> i last-start)
matches
(let [match?
(loop [j 0]
(or (= j (count string))
(and (= (.charAt string j) (.charAt text (+ i j)))
(recur (inc j)))))]
(recur (inc i) (if match? (conj matches i) matches)))))))
除了你的外循环中多余的j
,我不知道你的外循环与此有什么显著不同
作为一种风格
- 我已将复杂的内部
循环
表达式绑定到本地匹配?
。这将保留最终的
线路畅通
- 我使用了
和
和或
来简化表达式中的条件
- 我已经将条件
(如果匹配?…)
下推到
外部复发
注
您可以使用get
而不是.charAt
来访问字符串中的字符。我没有进行完全的修改,但是有一件小事:(print“\n”(str(下划线print\u pos))“^Match!”)
更好地表达为(print(str“\n”(下划线print\u pos)“^Match!”)