On Jan 30, 3:18 am, Robert McIntyre <[email protected]> wrote:
> I see, so you wanted to allow some subset of the optional arguments.
>
> Might I recommend the following?
> Sets are already functions that check for inclusion of the objects on
> which you call them, so instead of (contains? some-set ele) just
> (some-set ele) will work. Also, upon actually making a typo you just
> get the statement that (contains? #{:a :b} each) has failed, while I
> think it would be nicer if it actually showed the offending misspelled
> keyword. Unfortunately implementing this proved harder than I expected
> and the best I could come up with was:
>
> (defn hello
> [& {:keys [a b] :as input}]
> (dorun (map #(eval `(assert (#{:a :b} (quote ~%))))
> (keys input)))
> "hello")
>
> I'd be curious what the right way to to this is.
The version I have meanwhile come up with is this:
(defn verify-opt
"Verify that the optional arguments (keys) are from a known set of
keywords."
[known-coll input-coll]
(let [known-set (if (set? known-coll) known-coll
(into #{} known-coll))]
(doseq [each (if (map? input-coll)
(keys input-coll)
input-coll)]
(when-not (known-set each)
(throw (IllegalArgumentException.
(format "Invalid optional argument key %s, Allowed
keys: %s"
each
(with-out-str (pp/pprint known-set)))))))))
And to use this:
(defn hello
[& {:keys [a b] :as input}]
(verify-opt #{:a :b} input)
"hello")
The eval bit is succinct - I will try that out.
Regards,
Shantanu
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en