Hi All,
I have a couple of functions that return map with the same keywords. This an example how it looks like:
(defn my-func1 [x & {:as extra}]
{:some-number x ; example of some logic inside
:foo "foo"
:bar "bar"})
(defn my-func2 [x y & {:as extra}]
{:some-number (+ x y) ; example of some logic inside
:foo "foo"
:bar "bar"})
(defn my-func3 [x y z & {:as extra}]
{:some-number (+ x y z) ; example of some logic inside
:foo "foo"
:bar "bar"})
I would like to create an alternative version of those functions. Based on my understanding the Clojure way / func. programming way is to create a function from a function which in normal circumstances is easy but in this case it’s tricky since the generated functions need to have different number of parameters. My implementation looks like this:
(defn func-returning-some-number
[func arg-count]
(case arg-count
1 (fn [x & {:as extra}]
(let [{:keys [some-number foo bar]} (func x)]
(if (> some-number 3) ; example of some logic inside
some-number
:something)))
2 (fn [x y & {:as extra}] ; <= number of arguments is the only thing that is different
(let [{:keys [some-number foo bar]} (func x y)]
(if (> some-number 3)
some-number
:something)))
3 (fn [x y z & {:as extra}] ; <= number of arguments is the only thing that is different
(let [{:keys [some-number foo bar]} (func x y z)]
(if (> some-number 3)
some-number
:something)))))
and then I use it like this:
(def my-func1-not-returning-map
(func-returning-some-number my-func1 1))
(def my-func2-not-returning-map
(func-returning-some-number my-func2 2))
(def my-func3-not-returning-map
(func-returning-some-number my-func3 3))
You can clearly see that my implementation of func-returning-some-number
is bad bad bad since I’m Ctrl+c/v a block of code based on how many parameters the generated function should have. Could you please tell me is there a better way to do that?
Thank you.
Allan