Search code examples
clojure

Understanding Clojure partial


I'm reading the Clojure Programming book. I'm at an example about partials and it go like this:

(def only-strings (partial filter string?))

The thing is, if the i write the next function:

(defn only-strings [x] (filter string? x))

I can have the same result:

user=> (only-strings [6 3 "hola" 45 54])
("hola")

What are the benefits of using a partial here? Or the example is just to simple to show them? Could somebody please give me an example where a partial would be useful. Many thanks.


Solution

  • The benefits of partial in this case is that you can fix the first argument and bind it to string?.

    That's even all partial does. Predefining the first parameters as you can see in yours and in Arthur's example.

    (def foo (partial + 1 2))
    
    (foo 3 4)    ;; same as (+ 1 2 3 4)
    ;; > 10
    

    With partial I bound the first two arguments to 1 and 2 in this case.

    Why could this be useful?

    You may want to use map or apply on a function, which takes two arguments. This would be very bad, because map and apply take a function, which one needs one argument. So you might fix the first argument and use partial for this and you get a new function which only needs one argument. So it can be used with map or apply.

    In one of my projects I had this case. I thought about using partial or an anonymous function. As I only needed it in one case, I used a lambda. But if you need it more than one time, than defining a new function with partial would be very useful. Also it is more readable.