2
; common/math.clj
(defn nths
  "Returns a collection of values for each idx in idxs. Throws an error if any one idx is out of bounds."
  [coll idxs]
  (map #(nth coll %) idxs))

; nrepl
common.math> (try (/ 1 0)
     (catch Exception e (prn "in catch"))
     (finally (prn "in finally")))
"in catch"
"in finally"
nil
common.math> (try (nths '(5 6 7 8 9) '(0 5))
     (catch Exception e (prn "in catch"))
     (finally (prn "in finally")))
"in finally"
IndexOutOfBoundsException   clojure.lang.RT.nthFrom (RT.java:784)
common.math> (nths '(5 6 7 8 9) '(0 1 3))
(5 6 8)
common.math> *clojure-version*
{:major 1, :minor 5, :incremental 0, :qualifier "alpha4"}

我无法弄清楚第二个 expr 出了什么问题。我期待它会再次打印:

"in catch"
"in finally"

运行单元测试时也会发生同样的事情:

lein test unittest.common.math

FAIL in (test-nths) (math.clj:87)
expected: (thrown? IndexOutOfBoundsException (nths (quote (5 6 7 8 9)) (quote (0 5))))
  actual: nil

这应该通过。

4

2 回答 2

3

Nths 是惰性的,因此当您的 repl 尝试打印结果时,该函数实际上会运行:

core> (def result (try (nths '(5 6 7 8 9) '(0 5))
                        (catch Exception e (prn "in catch"))
                        (finally (prn "in finally"))))
"in finally"
#'core/result
core> result
; Evaluation aborted.

您可以在其中捕获异常,nths或者在使用它时捕获它更有意义

rsadl.core> (def result (try (nths '(5 6 7 8 9) '(0 5))
                        (catch Exception e (prn "in catch"))
                        (finally (prn "in finally"))))
"in finally"
#'core/result
core> (try (println result) (catch Exception e (prn "in catch")))
("in catch"
nil

或者正如 number23_cn 指出的那样,只要您不需要它因为其他原因而变得懒惰,您就可以在创建它时实现结果。

于 2012-08-28T00:49:30.323 回答
1
(try (doall (nths '(5 6 7 8 9) '(0 5)))
     (catch Exception e (prn "in catch"))
     (finally (prn "in finally")))
"in catch"
"in finally"
nil
user=> 

因为地图返回惰性序列?

于 2012-08-28T00:32:58.110 回答