Clojure - Partial

- - posted in clojure | Comments

Currying, partially applying arguments to functions, in Clojure.

The function partial accepts a function and some, but not all, of the arguments for that function. It returns a new function which accepts the remaining arguments. This is known as currying.

Using the function <, which accepts two arguments, as an example we can use partial to apply to the first argument and return a new function which accepts the second.

The function < accepts two arguments:

1
(< 25 10) ; false

We can create a new function with just 25 applied:

1
(partial < 25) ; fn

If we define a var and store the function returned by partial we can use it as follows:

1
2
3
4
(def greater-than-25 (partial < 25))

(greater-than-25 10)  ; false
(greater-than-25 100) ; true

Since partial returns a function it can be used with high-order functions such as map.

1
(map (partial * 10) [10 20 30 40]) ; 100 200 300 400

The function map accepts a function (which accepts one argument) and a collection, the function is applied to each item in the collection.

Docs: https://clojuredocs.org/clojure.core/partial

Comments