Search code examples
clojuredestructuring

In Clojure, can a default value be provided while using sequential destructuring?


Seems like providing a default value in Associative destructuring is well documented. https://clojure.org/guides/destructuring

Any known way to supply a default value in sequential destructuring?

For instance:

    (let [[hey you guys] ["do" "re"]]
      (println hey)
      (println you)
      (println guys))

Output:
do
re
nil

How would you provide a default value for 'guys'?

Have tried

(let [[hey you (or guys "me")] ["do" "re"]]

(let [[hey you #(or % "me")] ["do" "re"]]

and a few variations of

(let [[hey you guys :or "me"] ["do" "re"]]

Thanks!


Solution

  • No I don't believe there is a way to offer default values in non-associative destructuring.

    There would be more than one way to accomplish that, depending on what you're after. The closest to the snippets you provide might be:

    (let [input ["do" "re"]
          defaults ["def1" "def2" "def3" "def4"]
          [hey you guys] (concat input (drop (count input) defaults))]
      (println hey you guys)) ;; do re def3
    

    If you only have a default value for the 3rd arg, then you can use:

    (let [[hey you guys] (conj ["do" "re"] "def3")]
      (println hey you guys)) ;; do re def3
    

    or

    (let [[hey you guys] ["do" "re"]
          guys (or guys "def3")]
      (println hey you guys)) ;; do re def3