(defn assoc-if [pred coll kv] (if (pred coll k) (assoc coll kv) coll)) (defn assoc-if-new [coll kv] (assoc-if (complement contains?) coll kv))
You made a few mistakes:
IN
(defn assoc-if [pred coll kv] (if pred (assoc coll kv) coll))
... pred not called. Not being false and nil , its function value will evaluate to true. Therefore, the function will always return (assoc coll kv) .
IN
(defn assoc-if-new [coll kv] (assoc-if (not (contains? coll k)) coll kv))
... the first argument of assoc-if should be a predicate - a function that returns the value used for its truth or falsehood. (not (contains? coll k)) will generate a boolean, causing an error when assoc-if tries to call it a function.
- Do not specify arguments explicitly:
assoc-if calls inside. - If you want to invert the logical result, you need to adapt the function
contains? to a function that returns a logically inverted result. The standard complement function does this.
source share