代码之家  ›  专栏  ›  技术社区  ›  hawkeye

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

  •  11
  • hawkeye  · 技术社区  · 11 年前

    在菲尔·哈格伯格的( technomancy ) gripes file 他对Clojure作了如下陈述:

    nil无处不在,导致难以找到源代码的bug

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

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

    (defn myfunc [myarg1]
      (when (nil? myarg1) 
        (throw (Exception. "nil arg for myfunc")))
      (prn "done!"))
    

    这两行额外的每一个参数都散发着样板的味道。是否有通过元数据或宏删除它们的惯用方法?

    我的问题是 有没有一种快速的方法来检查Clojure函数中的nil参数?

    1 回复  |  直到 11 年前
        1
  •  8
  •   tangrammer    11 年前

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

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

    适应您的要求:

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

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

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