How to check if a function is partial?

Is it possible to check if something is a partial function in Clojure?

Would it be better to have something like (partial? (partial + 10))?

Thanks in advance

+5
source share
3 answers

No, because functions created by partial ones are just “normal” functions. You could use some metadata for it, for example:

(defn partial2 [f & more]
  (with-meta (apply partial f more) {:partial true}))

(def partial-plus (partial2 + 1 2))

(meta partial-plus) ;;=> {:partial true}

I didn’t think about the consequences of this approach, though ...

Kotarak has developed a nicer solution that works, but not always. For example, take this:

(partial? (partial + 1)) ;;=> true
(partial? (partial + 1 2)) ;;=> false

It works:

(defn partial? [f]
  (let [[fst snd] (-> (class f) (.getName) (string/split #"\$"))]
    (= ["clojure.core" "partial"] [fst snd])))

when string / split is a split function from clojure.string (1.3) or clojure.contrib.str-utils2 (1.2).

+16
source

You can hack.

user=> (let [partial-classes (map class [(partial + 1)
                                         (partial + 1 2)
                                         (partial + 1 2 3)
                                         (partial + 1 2 3 4)])]
         (defn partial?
           [x]
           (some #(instance? % x) partial-classes)))
#'user/partial?
user=> (partial? (partial - 1))
true
user=> (partial? (partial - 1 2))
true
user=> (partial? (partial - 1 2 3))
true
user=> (partial? (apply partial - 1 2 [3 4 5]))
true

EDIT: . , partial, .

+5

Functions created by partial ones are just normal functions, but if you lean on it, maybe something like this can help?

(defn partial?
  [f]
  (clojure.contrib.string/substring? "partial" (str (class f))))

Disclaimer: I don't know if something like this is insane.

+2
source

All Articles