如何在 Clojure 中为函数参数创建默认值 [英] How to create default value for function argument in Clojure
本文介绍了如何在 Clojure 中为函数参数创建默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我带着这个:
<前>(定义字符串->整数 [str & [base]](Integer/parseInt str (if (nil? base) 10 base)))(字符串-> 整数10")(字符串->整数FF"16)但这一定是一个更好的方法.
解决方案
如果签名的数量不同,一个函数可以有多个签名.您可以使用它来提供默认值.
(定义字符串->整数([s] (字符串-> 整数 s 10))([s base] (Integer/parseInt s base)))
注意,假设 false
和 nil
都被认为是非值,(if (nil? base) 10 base)
可以缩短到 (if base base 10)
,或者进一步到 (or base 10)
.
I come with this:
(defn string->integer [str & [base]] (Integer/parseInt str (if (nil? base) 10 base))) (string->integer "10") (string->integer "FF" 16)
But it must be a better way to do this.
解决方案
A function can have multiple signatures if the signatures differ in arity. You can use that to supply default values.
(defn string->integer
([s] (string->integer s 10))
([s base] (Integer/parseInt s base)))
Note that assuming false
and nil
are both considered non-values, (if (nil? base) 10 base)
could be shortened to (if base base 10)
, or further to (or base 10)
.
这篇关于如何在 Clojure 中为函数参数创建默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文