【Clojure 基本知識】 關於函數參數的各類高級用法

關於Clojure函數參數用法,學習中一些總結,無廢話,直接看代碼:函數

1、接受不定參數學習

;;接受不定參數
(defn f0[& pms]
    (println "params count=" (count pms) " type pms=" (type pms))
  (doseq [pm pms]
        (println pm)
    )
)

;;調用示例spa

;;調用示例
user=> (f0 "abc" 111 :err) params count= 3 type pms= clojure.lang.ArraySeq abc 111 :err nil user=>

2、接受map參數,map可爲空或缺失部分或所有關鍵字,解構出的參數值爲nilcode

;;接受map參數,map可爲空或缺失關鍵字,解構出的參數值爲nil
(defn f1[pm  {:keys [key value]}]
 (println "pm->" pm)
 (println "key->" key)
 (println "value->" value) 
)

;;調用示例blog

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=>

3、接受map參數,爲解構參數設置默認值class

;;接受map參數,爲解構參數設置默認值
(defn f11[pm  {:keys [key value] :or {key "def-key" value "def-value"}}]
 (println "pm->" pm)
 (println "key->" key)
 (println "value->" value) 
)

;;調用示例clojure

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=>

4、可選命名參數map

;;可選命名參數
(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=>

5、有默認值的可選命名參數命名

;;有默認值的可選命名參數
(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=>
相關文章
相關標籤/搜索