Recursion 从递归测试抛出
我无法捕获来自Recursion 从递归测试抛出,recursion,clojure,Recursion,Clojure,我无法捕获来自map的第二个递归调用的抛出。 由于某些原因,异常会从(调用rec(第一个节点))冒泡,但不会从(映射调用rec节点)冒泡 考虑以下示例: (deftest recursion-test (testing "Testing recursion throws" ;; => OK (is (thrown? Exception (map #(throw (Exception. "e") [:a :b]))
map
的第二个递归调用的抛出。
由于某些原因,异常会从(调用rec(第一个节点))
冒泡,但不会从(映射调用rec节点)
冒泡
考虑以下示例:
(deftest recursion-test
(testing "Testing recursion throws" ;; => OK
(is (thrown? Exception
(map #(throw (Exception. "e") [:a :b])))))
(testing "Testing throws from recursion lvl 1" ;; => OK
(is (thrown?
Exception
(letfn [(call-rec [node]
(cond
(vector? node)
(do
(throw (Exception. "e"))
(map call-rec node))
:else
node))]
(call-rec [:one :two])))))
(testing "Testing throws from map recursion lvl 2" ;; => FAILURE
(is (thrown? Exception
(letfn [(call-rec [node]
(cond
(vector? node)
(map call-rec node)
:else
(throw (Exception. "e"))
))]
(call-rec [:one :two])))))
(testing "Testing throws from first recursion lvl 2" ;; => OK
(is (thrown? Exception
(letfn [(call-rec [node]
(cond
(vector? node)
(call-rec (first node))
:else
(throw (Exception. "e"))
))]
(call-rec [:one :two]))))))
懒惰。形式
(map call-rec node)
创建一个从未实现的惰性序列,因此从未有机会抛出异常。请尝试以下版本:
(mapv call-rec node)
或者使用以下方法实现调用rec
之外的顺序:
(doall (call-rec [:one :two]))
另外值得一提的是,代码中还有其他bug。例如
(map#(throw(Exception.e)[:a:b]))
应该是(map(fn[#](throw(Exception.e))[:a:b])
<带有一个参数的代码>映射将在Clojure 1.7中创建映射传感器。