【问题标题】:Is there a quick way to check for nil args in a Clojure function?有没有一种快速的方法来检查 Clojure 函数中的 nil args?
【发布时间】:2014-03-06 10:27:13
【问题描述】:

在 Phil Hagelberg 的 (technomancy) gripes file 中,他对 Clojure 进行了如下陈述:

nil 无处不在,导致难以找到源头的错误

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

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

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

每个参数的这两行额外的样板文件臭气熏天。有没有一种通过元数据或宏删除它们的惯用方法?

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

【问题讨论】:

    标签: clojure null


    【解决方案1】:

    对于这些情况,有一个基于 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 library core.contracts,一个更复杂的工具

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

    【讨论】:

    • 当 clojure 1.6 出现时,您可以替换 (not (nil?x)) 一些吗?
    • @dAni 看来你是对的,因为我可以在 clojure 1.6 更改 github.com/clojure/clojure/blob/master/…987654324@ 上看到
    • {:pre [(not (nil? x))]} 可以简化为{:pre [x]}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-19
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 2021-01-28
    • 2011-09-24
    • 1970-01-01
    相关资源
    最近更新 更多