我在为下面的递归函数提供边缘情况时遇到了一个问题,该函数搜索哈希图和其他类似的键、值存储。
(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))))发布于 2012-11-18 22:03:24
你需要在你的条件函数中处理nil。为此,您可以使用fnil。fnil用一些默认值替换了nil。所以你可以试试:
(fnil #(> (.length %) 4) "")如果这个条件函数接收到nil,它会用空字符串"“替换nil,然后调用函数#(> (.length %) 4)。
此外,您还可以使用count来代替.length。对于nil,Count返回0:
(count "123") => 3
(count nil) => 0https://stackoverflow.com/questions/13440764
复制相似问题