Fork me on GitHub
#beginners
<
2023-10-17
>
Sahil Dhanju20:10:58

A few times now I've had a multi arity function where I had a let binding in each arity that was basically the same. Is there a way to only have to write this let binding once for all arities?

seancorfield20:10:04

Show us code. Hard to know what you're describing otherwise.

seancorfield20:10:35

(I haven't needed "a let binding in each arity that was basically the same" so I'm not sure what you're trying to do)

Sahil Dhanju20:10:43

(defn format-query
    ([a] (let [calculated-a (somefunction a)
               other-stuff-based-on-calculated-a (-> calculated-a
                                                     otherfunction
                                                     str)]
             (format query-defined-elsewhere calculated-a other-stuff-based-on-calculated-a "")))
    ([a b] (let [calculated-a (somefunction a)
                 other-stuff-based-on-calculated-a (-> calculated-a
                                                       otherfunction
                                                       str)]
               (format query-defined-elsewhere calculated-a other-stuff-based-on-calculated-a b))))

Sahil Dhanju20:10:33

I basically format the query in the exact same way between the two but have the additional b parameter

Bobbi Towers20:10:21

You can have one arity call the other passing the missing param, i.e.

(defn format-query
  ([a] (format-query a ""))
  ([a b] (let [calculated-a (somefunction a)
               other-stuff-based-on-calculated-a (-> calculated-a
                                                     otherfunction
                                                     str)]
           (format query-defined-elsewhere calculated-a other-stuff-based-on-calculated-a b))))

5