Skip to content

Instantly share code, notes, and snippets.

@matstani
Created July 18, 2013 06:56
Show Gist options
  • Save matstani/6027226 to your computer and use it in GitHub Desktop.
Save matstani/6027226 to your computer and use it in GitHub Desktop.
Clojureで引数のデフォルト値を指定する
;; 引数の個数(アリティ)でわける方法
(defn myfunc1
([arg] (myfunc1 arg "default"))
([arg opt] (format "arg=[%s] opt=[%s]" arg opt)))
(myfunc1 "argument")
; => "arg=[argument] opt=[default]"
(myfunc1 "argument" "option")
; => "arg=[argument] opt=[option]"
;; destructuringでデフォルト値を指定する方法
(defn myfunc2
[arg & {:keys [opt1 opt2] :or {opt1 "default1" opt2 "default2"}}]
(format "arg=[%s] opt1=[%s] opt2=[%s]" arg opt1 opt2))
(myfunc2 "argument")
; => "arg=[argument] opt1=[default1] opt2=[default2]"
(myfunc2 "argument" :opt1 "option1")
; => "arg=[argument] opt1=[option1] opt2=[default2]"
(myfunc2 "argument" :opt2 "option2")
; => "arg=[argument] opt1=[default1] opt2=[option2]"
(myfunc2 "argument" :opt1 "option1" :opt2 "option2")
; => "arg=[argument] opt1=[option1] opt2=[option2]"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment