clojure - Variadic function with keyword arguments -


i'm newbie clojure , wondering if there way define function can called this:

(strange-adder 1 2 3 :strange true) 

that is, function can receive variable number of ints , keyword argument.

i know can define function keyword arguments way:

(defn strange-adder   [a b c & {:keys [strange]}]   (println strange)   (+ b c)) 

but function can receive fixed number of ints.

is there way use both styles @ same time?

unfortunately, no.

the & destructuring operator uses after on argument list not have ability handle 2 diferent sets of variable arity destructuring groups in 1 form.

one option break function several arities. though works if can arrange 1 of them variadic (uses &). more universal , less convenient solution treat entire argument list 1 variadic form, , pick numbers off start of manually.

user> (defn strange-adder         [& args]          (let [nums (take-while number? args)                opts (apply hash-map (drop-while number? args))                strange (:strange opts)]           (println strange)               (apply + nums))) #'user/strange-adder user> (strange-adder 1 2 3 4 :strange 4) 4 10 

Comments

Popular posts from this blog

java - activate/deactivate sonar maven plugin by profile? -

python - TypeError: can only concatenate tuple (not "float") to tuple -

java - What is the difference between String. and String.this. ? -