0

I'm trying to define a function with optional parameters and each optional also has a default if it is not passed in. but i cannot get it to compile, and cannot find anything on the web to suggest something that will work.

here is what i have

defn test-optional-default-params [manA manB manC & [optA optB optC optD optE]
                                   :or {[optA optAdef
                                        optB optBdef
                                        optC optCdef
                                        optD optDdef
                                        optE optEdef]}]

(prn (str "manB->" manB ", mnC->" manC ", optA->" optA ", optB->" optB ", optC->" optC ", optD->" optD ", optE->" optE)))

f1wade
  • 2,877
  • 6
  • 27
  • 43

2 Answers2

2

You can use

(defn f [a b & {:keys [c d e] :or {c defaultc d defaultd e defaulte}}]
  blabla)

But you will have to do

(f 1 2 :c 3 :d 4 :e 5) 

So you can maybe do something like this (I tried with a basic function : addition) :

(defn add-rest* [c d e]
  (+ c d e))

(def add-rest*
  (fnil add-rest* 0 0 0))

(defn add
  [a b & [c d e]]
  (+ a b (add-rest c d e)))

(add 1 1) ;; 2
(add 1 1 1) ;; 3
(add 1 1 1 1) ;; 4
Joseph Yourine
  • 1,301
  • 1
  • 8
  • 18
1

You can use multi-arity functions, so example with addition with default values of 0 becomes:

(defn f+
  ([a b]        (f+ a b 0 0 0))
  ([a b c]      (f+ a b c 0 0))
  ([a b c d]    (f+ a b c d 0))
  ([a b c d e]  (+ a b c d e))) 

Replace + above with desired function of five variables. Usage of the above becomes:

(f+ 1 2)         ;; 3
(f+ 1 2 3)       ;; 6
(f+ 1 2 3 4)     ;; 10
(f+ 1 2 3 4 5)   ;; 15

Note: also discussed previously with additional options

Community
  • 1
  • 1
DarrylG
  • 16,732
  • 2
  • 17
  • 23