我在为以下搜索哈希映射和其他类似键、值存储的递归函数提供边缘案例时遇到问题。
(def hashbrownies
{"Mary","Dave"
"Dave","Anne"
"Anne","Tim"})
目前的方法
(defn recursive-lookup
[key-lst search-func conditional]
(let [next-key (search-func (first key-lst))]
(if (conditional next-key)
(reverse key-lst)
(recur (cons next-key key-lst) search-func conditional))))
有效的例子
>> (recursive-lookup ["Mary"] #(hashbrownies %) (partial = nil))
=> ("Mary" "Dave" "Anne" "Tim")
>> (recursive-lookup ["Mary"] #(hashbrownies %) #(< (.length %) 4))
=> ("Mary" "Dave" "Anne")
有问题的:
>> (recursive-lookup ["Mary"] #(hashbrownies %) #(> (.length %) 4))
=> NullPointerException clojure.lang.Reflector.invokeNoArgInstanceMember (Reflector.java:296)
我可以看出问题所在:由于无法满足条件,该函数#(> (.length %) 4)
将nil
(最后一个可能的返回值)作为参数。但是作为 Clojure 的新手,我不知道如何解决这个问题。有没有惯用的方法?
解决方案:
(defn recursive-lookup
[key-lst search-func conditional]
(let [next-key (search-func (first key-lst))]
(if (or (nil? next-key)
(conditional next-key))
(reverse key-lst)
(recur (cons next-key key-lst) search-func conditional))))