Search code examples
clojurefunction-composition

Clojure : what am I missing from comp?


I'm currenthly trying to work with compand it looks like I am missing something. If I understand well, comp works in the same order as the mathematical composition, so (comp g f) is like g(f(x)).

Imagine I have a map like that

(def m {:a 1 :b nil :c 3})

I would like to use remove with a short nil-key? function to remove the entries which have nil values, so :

(into {} (remove nil-key? m)) = {:a 1 :c 3}

I tried to define nil-key? like that :

(defn nil-key? []
  (comp nil? second))

It returns an empty map (if I use filter, no map entry is removed)

Maybe I do not understand how the remove function works because I thught there was an hidden map.

Like : 1) first map second on the hashmap 2) tells if the value is nil 3) give the matching

I could do

(into {} (filter second m))

But is also removes false, which I want not.

Of course I can do it easily with a different approach but I would like to understand the comp function.

Thanks !

EDIT

The answer

(def nil-key?
  (comp nil? second))

The final function

(defn remove-nil-keys [map]
  (->> (remove nil-key? map)
       (into {})))

Solution

  • You have a mistake in your nil-key? definition. Your function returns a function that will produce a composed function:

    (defn nil-key? []
      (comp nil? second))
    

    If you want to use it in this form you would have to call nil-key? in order to produce your predicate function:

    (into {} (remove (nil-key?) m))
    ;; => {:a 1, :c 3}
    

    Instead you should define a var with the result of composing the functions:

    (def nil-key? (comp nil? second))
    

    Then it will work correctly:

    (into {} (remove nil-key? m))
    ;; => {:a 1, :c 3}