Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Clojure partial

Tags:

clojure

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.

like image 273
roboli Avatar asked Mar 27 '14 18:03

roboli


People also ask

What is partial Clojure?

Clojure therefore has the partial function gives results similar to currying, however the partial function also works with variable functions. partial refers to supplying some number of arguments to a function, and getting back a new function that takes the rest of the arguments and returns the final result.

How do you define a list in Clojure?

List is a structure used to store a collection of data items. In Clojure, the List implements the ISeq interface. Lists are created in Clojure by using the list function.

How do you create a function in Clojure?

A function is defined by using the 'defn' macro. An anonymous function is a function which has no name associated with it. Clojure functions can be defined with zero or more parameters. The values you pass to functions are called arguments, and the arguments can be of any type.


1 Answers

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 your 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 needed it more than one time, than defining a new function with partial would be very useful.

like image 156
n2o Avatar answered Sep 30 '22 12:09

n2o