ハッシュマップや他の同様のキー、値ストレージを検索する次の再帰関数のエッジケースを提供するのに問題があります。
(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))))