有没有快速的方法来检查Clojure函数中的nil args?

haw*_*eye 8 null clojure

在Phil Hagelberg的(技术)抱怨文件中,他陈述了关于Clojure的以下内容:

零无处不在并导致难以找到源的错误

现在菲尔是一个聪明的人,他为Clojure社区做出了很多贡献,每个人都使用他的东西 - 所以我认为这值得深思.

管理函数的nil args的一种简单方法是抛出错误:

(defn myfunc [myarg1]
  (when (nil? myarg1) 
    (throw (Exception. "nil arg for myfunc")))
  (prn "done!"))
Run Code Online (Sandbox Code Playgroud)

这两个额外的行每个参数reek的样板.是否有通过元数据或宏删除它们的惯用方法?

我的问题是在Clojure函数中有没有快速检查nil args的方法?

tan*_*mer 7

对于这些情况,有一种基于clojure语言的解决方案:http: //clojure.org/special_forms#toc10

(defn constrained-sqr [x]
    {:pre  [(pos? x)]
     :post [(> % 16), (< % 225)]}
    (* x x))
Run Code Online (Sandbox Code Playgroud)

适应您的要求:

(defn constrained-fn [ x]
  {:pre  [(not (nil? x))]}
  x)
(constrained-fn nil)
=> AssertionError Assert failed: (not (nil? x))  ...../constrained-fn (form-init5503436370123861447.clj:1)
Run Code Online (Sandbox Code Playgroud)

还有@fogus contrib库core.contracts,一个更复杂的工具

本页更多信息http://blog.fogus.me/2009/12/21/clojures-pre-and-post/

  • 当clojure 1.6出现时,您可以替换(不是(零)x)某些? (3认同)