有没有一种快速的方法来检查 Clojure 函数中的 nil args? [英] Is there a quick way to check for nil args in a Clojure function?

查看:19
本文介绍了有没有一种快速的方法来检查 Clojure 函数中的 nil args?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Phil Hagelberg 的 (technomancy) gripes 文件 他陈述了以下关于 Clojure 的内容:

In Phil Hagelberg's (technomancy) gripes file he states the following about Clojure:

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

nil is everywhere and causes bugs that are difficult to find the source

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

Now Phil is a smart guy who has contributed a lot to the Clojure community, and everyone uses his stuff - so I thought this was worth pondering for a moment.

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

One easy way to manage nil args to a function is to throw an error:

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

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

These two extra lines per argument reek of boilerplate. Is there an idiomatic way to remove them via metadata or macros?

我的问题是是否有一种快速的方法可以检查 Clojure 函数中的零参数?

推荐答案

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

There is a clojure language based solution for these situations: 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,更多复杂的工具

And there is also the @fogus contrib library core.contracts, a more sophisticated tool

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

More info on this page http://blog.fogus.me/2009/12/21/clojures-pre-and-post/

这篇关于有没有一种快速的方法来检查 Clojure 函数中的 nil args?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆