关于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.ArraySeqabc111:errniluser=>
二、接受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-> abckey-> kkvalue-> 1niluser=> (f1 "abc" {:key "k2"})pm-> abckey-> k2value-> nilniluser=> (f1 "abc" {})pm-> abckey-> nilvalue-> nilniluser=>
三、接受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-> abckey-> kkvalue-> 1niluser=> (f11 "abc" {:key "k2"})pm-> abckey-> k2value-> def-valueniluser=> (f11 "abc" {})pm-> abckey-> def-keyvalue-> def-valueniluser=>
四、可选命名参数
;;可选命名参数(defn f2[pm & {:keys [key value]}] (println "pm->" pm) (println "key->" key) (println "value->" value) )
;;调用示例
user=> (f2 "abc" :key "kk" :value 1)pm-> abckey-> kkvalue-> 1niluser=> (f2 "abc" :key "k2")pm-> abckey-> k2value-> nilniluser=> (f2 "abc" )pm-> abckey-> nilvalue-> nilniluser=>
五、有默认值的可选命名参数
;;有默认值的可选命名参数(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-> abckey-> kkvalue-> 1niluser=> (f22 "abc" :key "k2")pm-> abckey-> k2value-> def-valueniluser=> (f22 "abc" )pm-> abckey-> def-keyvalue-> def-valueniluser=>