Search code examples
parametersclojuredefaultoption-type

defining an optional with a default


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


Solution

  • 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