如何在Clojure中为函数参数创建默认值 [英] How to create default value for function argument in Clojure

查看:164
本文介绍了如何在Clojure中为函数参数创建默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来这里:

 
(defn string-> integer [str&[base]]
(Integer / parseInt str(if(nil?base)10 base)))

(string-> integer10)
(string-> integerFF / pre>

但它必须是更好的方法。

解决方案

如果签名的不同,函数可以有多个签名。您可以使用它提供默认值。

 (defn string-> integer 
- >整数s 10))
([s base](Integer / parseInt s base)))

请注意,假设 false nil 都被认为是非值, (if(nil?base)10 base)可以缩短为(如果base base为10) (或基数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屋!

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