Hi Everybody,
Recently I wrote several functions like this:
(defn my-function
[my-input & {:keys [first-optional
second-optional
third-optional]
:or {first-optional false
second-optional false
third-optional false}}]
(if-let [result (call-something
my-input
{:first-different-name first-optional
:second-different-name second-optional
:third-different-name third-optional})]
result
(call-another my-input)))
They differed only in default values for opts (false
in example) and in the last function to call (call-another
in example).
I looked at the code realizing that there is a lot of text and a lot of duplicity among those functions but I wasn’t sure how to remove the duplicity since the duplicate code is not something that can be in an another function.
Then I realized I can do (defn foo [x] fn [ ... ] ...)
like this:
(defn create-my-function
[f default-value]
(fn [my-input & {:keys [first-optional
second-optional
third-optional]
:or {first-optional default-value
second-optional default-value
third-optional default-value}}]
(if-let [result (call-something
my-input
{:first-different-name first-optional
:second-different-name second-optional
:third-different-name third-optional})]
result
(f my-input))))
(def my-function1 (create-my-function call-another1 true))
(def my-function2 (create-my-function call-another2 false))
(def my-function3 (create-my-function call-another3 123))
Can anyone please tell me is (defn foo [x] fn [ ... ] ...)
a normal thing to do in Clojure?
Thank you.
Best regards,
Billy