我在为以下搜索 HashMap 和其他类似键值存储的递归函数提供边缘情况时遇到问题。
(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))))
最佳答案
您需要在条件函数中处理nil
。您可以使用fnil为了那个原因。 fnil
用一些默认值替换 nil。所以你可以尝试:
(fnil #(> (.length %) 4) "")
如果此条件函数接收到 nil
,它将用空字符串 ""替换 nil
,然后调用您的函数 #(> (.length %) 4)
.
您也可以使用count
代替.length
。对于 nil,Count 返回 0:
(count "123") => 3
(count nil) => 0
关于recursion - 递归地跟踪 HashMap clojure 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13440764/