测试从递归中抛出

时间:2015-02-19 15:21:09

标签: recursion clojure

我无法从map的第二次递归通话中捕获投掷。 出于某种原因,例外情况来自(call-rec (first node))但不来自(map call-rec node)

请考虑以下示例:

    (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]))))))

1 个答案:

答案 0 :(得分:3)

懒惰。表格

(map call-rec node)

创建一个永远不会实现的惰性序列,因此永远不会有机会抛出异常。尝试热切的版本:

(mapv call-rec node)

使用以下方法实现call-rec之外的序列:

(doall (call-rec [:one :two]))