I'm trying to create a multiple-arity function in Clojure that, if given a single vector argument, just applies another function to the vector; and if given a vector plus 1 or more functions, maps the composition of those functions over the vector then applies the third function. But somehow I don't seem to be able to access any optional argument outside the first.
Toy example code:
(defn times2 [num] (* 2 num))
(defn square [num] (* num num))
(defn plusfiveall [vec-of-nums] (map #(+ 5 %) vec-of-nums))
(defn toynums
([vec-of-nums]
(plusfiveall vec-of-nums))
([vec-of-nums & [funcs]]
(let [moremath (comp funcs)]
(plusfiveall (map moremath vec-of-nums)))))
What I think should happen:
(toynums [1 2 3]) = (6 7 8)
(toynums [1 2 3] times2) = (7 9 11)
(toynums [1 2 3] times2 square) = (7 13 23)
but while the first two of those examples work as expected, the third fails to apply square: instead I get (toynums [1 2 3] times2 square) --> (7 9 11)
In an attempt to drill down on the problem, I've also tried a version without the mapping, and have the same surprising behavior:
(defn comp-nomap
([num] (plusfive num))
([num & [funcs]]
(let [funmath (comp funcs)]
(plusfive (funmath num)))))
(comp-nomap 3) = 8 as expected
(comp-nomap 3 times2) = 11 as expected
but (comp-nomap 3 times2 square) also = 11, rather than 23 like it should be.
help? thanks!