Clojure Parameters with Optional Flags
clojure, keyword, parameters
Solution
Lists (as well as vectors and maps) are not a good choice of data structure for value-based lookups (will be linear time), that's why clojure.core doesn't have such functions.
Sets do provide fast value-based lookups via "contains?", so how about
(defn foo [value & flags]
(let [flags (set flags)]
(if (contains? flags :add-one)
(inc value)
value)))
If there won't be more than one flag, you can use destructuring like this:
(defn foo [value & [flag]] …)
Problem
What's the best way to implement keywords as optional flags to a function? I want to make function calls such as: ``` (myfunction 5) (myfunction 6 :do-this) (myfunction 3 :go-here) (myfunction 2 :do-this :do-that) ``` Using defn, I can define a function such as: ``` (defn myfunction [value & flags] ... ) ``` But the `flags` becomes a list. I can write my own function to search the list, but such a function isn't included in the core library, so I assume it's not idiomatic. What I'm using now: ``` (defn flag-set? [list flag] (not (empty? (filter #(= flag %) list)))) (defn flag-add [list flag] (cons flag list)) (defn flag-remove [list flag] (filter #(not= flag %) list)) ```