关于Clojure函数参数用法,学习中一些总结,无废话,直接看代码:
一、接受不定参数
;;接受不定参数 (defn f0[& pms] (println "params count=" (count pms) " type pms=" (type pms)) (doseq [pm pms] (println pm) ) )
;;调用示例
;;调用示例
user=> (f0 "abc" 111 :err) params count= 3 type pms= clojure.lang.ArraySeq abc 111 :err nil user=>
二、接受map参数,map可为空或缺失部分或全部关键字,解构出的参数值为nil
;;接受map参数,map可为空或缺失关键字,解构出的参数值为nil (defn f1[pm {:keys [key value]}] (println "pm->" pm) (println "key->" key) (println "value->" value) )
;;调用示例
user=> (f1 "abc" {:key "kk" :value 1}) pm-> abc key-> kk value-> 1 nil user=> (f1 "abc" {:key "k2"}) pm-> abc key-> k2 value-> nil nil user=> (f1 "abc" {}) pm-> abc key-> nil value-> nil nil user=>
三、接受map参数,为解构参数设置默认值
;;接受map参数,为解构参数设置默认值 (defn f11[pm {:keys [key value] :or {key "def-key" value "def-value"}}] (println "pm->" pm) (println "key->" key) (println "value->" value) )
;;调用示例
user=> (f11 "abc" {:key "kk" :value 1}) pm-> abc key-> kk value-> 1 nil user=> (f11 "abc" {:key "k2"}) pm-> abc key-> k2 value-> def-value nil user=> (f11 "abc" {}) pm-> abc key-> def-key value-> def-value nil user=>
四、可选命名参数
;;可选命名参数 (defn f2[pm & {:keys [key value]}] (println "pm->" pm) (println "key->" key) (println "value->" value) )
;;调用示例
user=> (f2 "abc" :key "kk" :value 1) pm-> abc key-> kk value-> 1 nil user=> (f2 "abc" :key "k2") pm-> abc key-> k2 value-> nil nil user=> (f2 "abc" ) pm-> abc key-> nil value-> nil nil user=>
五、有默认值的可选命名参数
;;有默认值的可选命名参数 (defn f22[pm & {:keys [key value] :or {key "def-key" value "def-value"}} ] (println "pm->" pm) (println "key->" key) (println "value->" value) )
;;调用示例
user=> (f22 "abc" :key "kk" :value 1) pm-> abc key-> kk value-> 1 nil user=> (f22 "abc" :key "k2") pm-> abc key-> k2 value-> def-value nil user=> (f22 "abc" ) pm-> abc key-> def-key value-> def-value nil user=>