本文介绍了Clojure 中数值参数的验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个clojure函数:

I have a clojure function:

(defn f [arg1 arg2]
  ...)

我想测试 arg1arg2 是否是数字(只有数字类型应该通过 - 而不是数字格式的字符串).当然,有很多方法可以做到这一点,但我想尽可能地地道.建议?

I would like to test if arg1 and arg2 are numeric (only numeric types should pass - not numerically formatted strings). There are, of course, a whole bunch of ways to do this, but I'd like to do it as idiomatically as possible. Suggestions?

我知道 :pre.任何关于这是否是处理此问题的适当/必要方式的评论将不胜感激.

I know about :pre. Any comment on whether or not that is an appropriate/necessary way to handle this would be appreciated.

推荐答案

先决条件可以做到:

(defn test [arg1 arg2]
  {:pre [(number? arg1) (number? arg2)]}
  (+ arg1 arg2))

(test 1 2)
=> 3

(test 1 "2")
=> Assert failed: (number? arg2)

有关文档,请参阅 http://clojure.org/special_forms#toc9.

这篇关于Clojure 中数值参数的验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 11:11